前言
今天看到一句这样的代码:
[].slice.call(document.querySelectorAll('li'), 0)
这是在干嘛?没看懂。搜了一下,大家说,这是在把DOM节点数组转为真正的数组。哦~ 我想起来了,好像是有这么回事,selector 返回的数组好像是叫「类数组」来着。
什么是类数组
类数组又叫伪数组,是形似数组,但不是数组的类数组对象。函数的 arguments 参数,以及 DOM 元素查找方法返回的 nodeList 对象都属于类数组。
类数组和数组的区别
类数组:有遍历方法、有 length 属性,但没有其他数组方法。
//类数组
const nodeList = document.querySelectorAll('li')
nodeList.__proto__
//数组
const list = [].slice.call(document.querySelectorAll('li'), 0)
list.__proto__
nodeList instanceof Array //false
list instanceof Array //true
通过输出原型我们可以看到,nodeList 的原型上只有几个遍历方法和 length 属性。
数组的原型链:list → Array.prototype → Object.prototype → null
nodeList 的原型链:nodeList → NodeList.prototype → Object.prototype → null
类数组转数组
除了上述 [].slice.call(document.querySelectorAll('li'), 0)
的方法以外,ES6 提供了更简便的方式:
- 使用扩展运算符
...
const newList = [...nodeList]
newList instanceof Array //true
- 使用
Array.from()
方法
const newList = Array.from(nodeList)
newList instanceof Array //true