此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

NodeList.prototype.forEach()

基线 广泛可用

自 2017年10月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

NodeList接口的 forEach() 方法按插入顺序为列表中的每个值对调用一次参数中给定的回调。

语法

js
forEach(callback)
forEach(callback, thisArg)

参数

callback

someNodeList的每一个元素执行函数。它接受以下三个参数:

currentValue

someNodeList中的当前元素。

currentIndex 可选

someNodeList中的currentValue所对应的索引值。

listObj 可选

someNodeListforEach() 方法中所属的 NodeList 对象。

thisArg 可选

传递 callback 的值一般用this值。

返回值

undefined.

示例

js
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");

上述代码会产生以下结果:

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

规范

规范
DOM
# interface-nodelist

浏览器兼容性

参见