forEach() 方法在 NodeList interface calls the callback given in parameter once for each value pair in the list, in insertion order.

句法

someNodeList.forEach(callback[, thisArg]);
					

参数

callback

A function to execute on each element of someNodeList . It accepts 3 parameters:

currentValue
The current element being processed in someNodeList .
currentIndex 可选
The index of the currentValue being processed in someNodeList .
listObj 可选
someNodeList that forEach() is being applied to.
thisArg 可选
Value to use as this when executing callback .

返回值

undefined .

范例

let node = document.createElement("div");
let kid1 = document.createElement("p");
let kid2 = document.createTextNode("hey");
let kid3 = document.createElement("span");
node.appendChild(kid1);
node.appendChild(kid2);
node.appendChild(kid3);
let list = node.childNodes;
list.forEach(
  function(currentValue, currentIndex, listObj) {
    console.log(currentValue + ', ' + currentIndex + ', ' + this);
  },
  'myThisArg'
);
					

The above code results in the following:

[object HTMLParagraphElement], 0, myThisArg
[object Text], 1, myThisArg
[object HTMLSpanElement], 2, myThisArg
					

Polyfill

This polyfill adds compatibility to all Browsers supporting ES5 :

if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = function (callback, thisArg) {
        thisArg = thisArg || window;
        for (var i = 0; i < this.length; i++) {
            callback.call(thisArg, this[i], i, this);
        }
    };
}
					

OR

if (window.NodeList && !NodeList.prototype.forEach) {
   NodeList.prototype.forEach = Array.prototype.forEach;
}
					

The above behavior is how many browsers actually implement NodeList.prototype.forEach() (Chrome, for example).

规范

规范 状态 注释
Web IDL
The definition of 'forEach' in that specification.
候选推荐 定义 forEach on iterable declarations

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
forEach Chrome 51 Edge 16 Firefox 50 IE No Opera 38 Safari 10 WebView Android 51 Chrome Android 51 Firefox Android 50 Opera Android 41 Safari iOS 10 Samsung Internet Android 5.0

图例

完整支持

完整支持

不支持

不支持

另请参阅

元数据

  • 最后修改: