在使用原生方法或者jquery方法获取DOM元素后,想像正常使用数组的方法对其遍历时,发现一些数组的遍历方法使用不了,如map ,push , pop等方法。使用后报错:.map is not a function
1、NodeList 对象在某些方面和数组非常相似,看上去可以直接使用从 Array.prototype 上继承的方法。然而,除了 forEach 方法,NodeList 没有这些类似数组的方法。通过一下方法判断NodeList 不是数组。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文档标题</title>
</head>
<body>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</body>
</html>
<script>
const nodeList= document.querySelectorAll('li');
console.log(nodeList instanceof Object) // true
console.log(nodeList instanceof Array) // false
console.log(Array.isArray(nodeList)) // false
//JavaScript 的继承机制是基于原型的,数组元素之所以有一些数组方法(比如 map和 push ),是因为它的原型链上有这些方法.
//通过下面的方法:
let rest = Object.getPrototypeOf(nodeList) //获取nodeList的原型
while(rest !== null ){
console.log(rest)
rest = Object.getPrototypeOf(rest)
}
console.log(rest)
</script>
//---------------------------------------------
可以得到 nodeList 的原型链是这样的:
nodeList–> NodeList.prototype --> Object.prototype --> null
而数组为:
myArray --> Array.prototype --> Object.prototype --> null
可以得出NodeList不是一个数组,而是一个类数组
2、常用的几种遍历方法
// 1、for
for(let i = 0;i<nodeList.length;i++){
console.log(nodeList[i])
}
// 2、forEach
nodeList.forEach(i=>console.log(i))
// 3、Array.prototype.map.call
Array.prototype.map.call(nodeList,i=>console.log(i))
// 4、for of
for(let i of nodeList){console.log(i)}
// 5、 Object.values
Object.values(nodeList).map(i=>console.log(i))
//打印出来都为 dom 元素