转载: 将 Node List 转换为数组 (Array)
# apply
querySelectorAll 方法返回一个类数组对象称为 node list。这些数据结构被称为 “类数组”,因为他们看似数组却没有类似 map 、 foreach 这样的数组方法。这是一个快速、安全、可重用的方法将 node list 转换为 DOM 元素的数组:
1 | const nodelist = document.querySelectorAll('div'); |
apply 方法可以在指定 this 时以数组形式向方法传递参数。MDN 规定 apply 可以接受类数组对象,恰巧就是 querySelectorAll 方法所返回的内容。如果我们不需要指定方法内 this 的值时传 null 或 0 即可。返回的结果即包含所有数组方法的 DOM 元素数组。
# slice
另外你可以使用 Array.prototype.slice 结合 Function.prototype.call 或 Function.prototype.apply , 将类数组对象当做 this 传入:
1 | const nodelist = document.querySelectorAll('div'); |
# …
如果你正在用 ES2015 你可以使用展开运算符 ...
1 | const nodelist = [...document.querySelectorAll('div')]; // 返回一个真正的数组 |