NodeList: forEach() 方法

Baseline 已廣泛支援

此功能已非常成熟,可在多種裝置和瀏覽器版本上使用。自 2017 年 10 月以來,它已在各大瀏覽器中可用。

NodeList 介面的 forEach() 方法會按照插入順序,為列表中的每一對值呼叫一次引數中給出的回撥函式。

語法

js
forEach(callback)
forEach(callback, thisArg)

引數

回撥

一個將在 someNodeList 的每個元素上執行的函式。它接受 3 個引數

currentValue

someNodeList 中正在處理的當前元素。

currentIndex 可選

someNodeList 中正在處理的 currentValue 的索引。

listObj 可選

正在應用 forEach()someNodeList

thisArg 可選

執行 callback 時用作 this 的值。

返回值

undefined.

示例

js
const node = document.createElement("div");
const kid1 = document.createElement("p");
const kid2 = document.createTextNode("hey");
const kid3 = document.createElement("span");

node.appendChild(kid1);
node.appendChild(kid2);
node.appendChild(kid3);

const 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

瀏覽器相容性

另見