NodeList 现在在所有主流浏览器中都有 forEach()
见nodeList forEach() on MDN。
原答案
这些答案都没有解释为什么 NodeList 不继承自 Array,因此允许它拥有 forEach 和所有其他的。
找到答案on this es-discuss thread。简而言之,它破坏了网络:
问题是代码错误地假定 instanceof 表示该实例是与 Array.prototype.concat 组合的数组。
Google 的 Closure 库中存在一个错误,导致几乎所有 Google 的应用都因此而失败。发现此问题后,该库已立即更新,但可能仍有代码与 concat 结合使用做出相同的错误假设。
也就是说,有些代码做了类似的事情
if (x instanceof Array) {
otherArray.concat(x);
} else {
doSomethingElseWith(x);
}
但是,concat 将“真实”数组(不是 instanceof Array)与其他对象区别对待:
[1, 2, 3].concat([4, 5, 6]) // [1, 2, 3, 4, 5, 6]
[1, 2, 3].concat(4) // [1, 2, 3, 4]
所以这意味着当 x 是 NodeList 时,上面的代码会中断,因为在它沿着 doSomethingElseWith(x) 路径之前,它沿着 otherArray.concat(x) 路径,它做了一些奇怪的事情,因为 x 不是'不是一个真正的数组。
一段时间以来,有人提出了Elements 类的提议,它是 Array 的真正子类,并将用作“新的 NodeList”。但是,至少目前是removed from the DOM Standard,因为由于各种技术和规范相关的原因,它还不可行。