所以我想要一个简单的方法来遍历节点列表,我一直讨厌我不能在节点列表上使用 forEach
。
所以,现在我这样做:Array.prototype.forEach.call(nodeList, callback)
。
对于索引,我这样做:Array.prototype.indexOf.call(nodeList, node)
。
几乎所有的事情我都在 nodeLists 上使用 Array.prototype。
但我想知道这些是否被视为 hack?
它们是正确的方法吗?
此外,假设我实际上不需要来自 nodeList 的数组,那么使用 Array.from(nodeList).forEach(callback)
是否有优势?
最佳答案
Array.prototype.forEach.call(nodeList, callback)
将在节点列表上应用 forEach
的逻辑。 forEach
中只有一个 for
循环,从索引 0
到 this.length
并调用回调每个项目。此方法调用 forEach
将节点列表作为其 this
值传递,因为节点列表具有与数组相似的属性(length
和 0
、1
、...),一切正常。
Array.from(nodeList).forEach(callback)
将从节点列表创建一个新数组,然后在该新数组上使用 forEach
。第二种方法可以分为两条不言自明的行:
var newArray = Array.from(nodeList); // create a new array out of the node list
newArray.forEach(callback); // call forEach on the new array
第一种方法更好,因为它不会创建额外的不需要的资源,而且它直接作用于节点列表。
关于javascript - 遍历 NodeList : Array. prototype.forEach.call() vs Array.from().forEach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43449971/