为什么 nodelist 没有 for each?

我正在编写一个简短的脚本来更改 <abbr>元素的内部文本,但是发现 nodelist没有 forEach方法。我知道 nodelist不是从 Array继承来的,但是 forEach不是一个很有用的方法吗?是否有一个我不知道的特殊的实现问题阻止了将 forEach添加到 nodelist

注意: 我注意到 Dojo 和 jQuery 都以某种形式为其节点列表提供了 forEach。由于限制,我不能使用任何一个。

73784 次浏览

In short, its a design conflict to implement that method.

From MDN:

Why can't I use forEach or map on a NodeList?

NodeList are used very much like arrays and it would be tempting to use Array.prototype methods on them. This is, however, impossible.

JavaScript has an inheritance mechanism based on prototypes. Array instances inherit array methods (such as forEach or map) because their prototype chain looks like the following:

myArray --> Array.prototype --> Object.prototype --> null (the prototype chain of an object can be obtained by calling several times Object.getPrototypeOf)

forEach, map and the likes are own properties of the Array.prototype object.

Unlike arrays, NodeList prototype chain looks like the following:

myNodeList --> NodeList.prototype --> Object.prototype --> null

NodeList.prototype contains the item method, but none of the Array.prototype methods, so they cannot be used on NodeLists.

Source: https://developer.mozilla.org/en-US/docs/DOM/NodeList (scroll down to Why can't I use forEach or map on a NodeList?)

NodeList is part of the DOM API. Look at the ECMAScript bindings which apply to JavaScript as well. http://www.w3.org/TR/DOM-Level-2-Core/ecma-script-binding.html. The nodeList and a read-only length property and item(index) function to return a node.

The answer is, you have to iterate. There is no alternative. Foreach will not work. I work with Java DOM API bindings and have the same problem.

You can consider creating a new array of nodes.

  var nodeList = document.getElementsByTagName('div'),


nodes = Array.prototype.slice.call(nodeList,0);


// nodes is an array now.
nodes.forEach(function(node){


// do your stuff here.


});

Note: This is just a list/array of node references we are creating here, no duplicate nodes.

  nodes[0] === nodeList[0] // will be true

You can do

Array.prototype.forEach.call (nodeList, function (node) {


// Your code here.


} );

If you would like using forEach on NodeList, just copy that function from Array:

NodeList.prototype.forEach = Array.prototype.forEach;

Thats all, now you can use it at the same manner you would for Array:

document.querySelectorAll('td').forEach(function(o){
o.innerHTML = 'text';
});

NodeList now has forEach() in all major browsers

See nodeList forEach() on MDN.

Original answer

None of these answers explain why NodeList doesn't inherit from Array, thus allowing it to have forEach and all the rest.

The answer is found on this es-discuss thread. In short, it breaks the web:

The problem was code that incorrectly assumed instanceof to mean that the instance was an Array in combination with Array.prototype.concat.

There was a bug in Google's Closure Library which caused almost all Google's apps to fail due to this. The library was updated as soon as this was found but there might still be code out there that makes the same incorrect assumption in combination with concat.

That is, some code did something like

if (x instanceof Array) {
otherArray.concat(x);
} else {
doSomethingElseWith(x);
}

However, concat will treat "real" arrays (not instanceof Array) differently from other objects:

[1, 2, 3].concat([4, 5, 6]) // [1, 2, 3, 4, 5, 6]
[1, 2, 3].concat(4) // [1, 2, 3, 4]

so that means that the above code broke when x was a NodeList, because before it went down the doSomethingElseWith(x) path, whereas afterward it went down the otherArray.concat(x) path, which did something weird since x wasn't a real array.

For some time there was a proposal for an Elements class that was a real subclass of Array, and would be used as "the new NodeList". However, that was removed from the DOM Standard, at least for now, since it wasn't feasible to implement yet for a variety of technical and specification-related reasons.

Never say never, it's 2016 and the NodeList object has implemented a forEach method in latest chrome (v52.0.2743.116).

It's too early to use it in production as other browser don't support this yet (tested FF 49) but I would guess that this will be standardized soon.

My solution:

//foreach for nodeList
NodeList.prototype.forEach = Array.prototype.forEach;
//foreach for HTML collection(getElementsByClassName etc.)
HTMLCollection.prototype.forEach = Array.prototype.forEach;

In ES2015, you can now use forEach method to the nodeList.

document.querySelectorAll('abbr').forEach( el => console.log(el));

See The MDN Link

However if you want to use HTML Collections or other array-like objects, in es2015, you can use Array.from() method. This method takes an array-like or iterable object (including nodeList, HTML Collections, strings etc) and returns a new Array instance. You can use it like this:

const elements = document.getElementsByTagName('abbr');
Array.from(elements).forEach( el => console.log(el));

As Array.from() method is shimmable, you can use it in es5 code like this

var elements = document.getElementsByTagName('abbr');
Array.from(elements).forEach( function(el) {
console.log(el);
});

For details, see the MDN page.

To check current browser support.

OR

another es2015 way is to use spread operator.

[...document.querySelectorAll('abbr')].forEach( el => console.log(el));

MDN spread operator

Spread Operator - Browser Support

Check MDN for NodeList.forEach specification.

NodeList.forEach(function(item, index, nodeList) {
// code block here
});

In IE, use akuhn's answer:

[].forEach.call(NodeList, function(item, index, array) {
// code block here
});