DOMTokenList: forEach() 方法

Baseline 已廣泛支援

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

DOMTokenList 介面的 forEach() 方法會呼叫引數中提供的回撥函式一次,用於列表中的每個值對,按插入順序執行。

語法

js
forEach(callback)
forEach(callback, thisArg)

引數

回撥

為每個元素執行的函式,最終接受三個引數

currentValue

陣列中正在處理的當前元素。

currentIndex

陣列中正在處理的當前元素的索引。

listObj

正在應用 forEach() 的陣列。

thisArg 可選

執行 callback 時用作 this 的值。

返回值

無。

示例

在以下示例中,我們使用 Element.classList 來檢索設定在 <pre> 元素上的類列表,將其作為 DOMTokenList。然後,我們使用 forEach() 檢索包含這些值的迭代器,並在 forEach() 內部函式中將每個值寫入 <pre>Node.textContent

HTML

html
<pre class="a b c"></pre>

JavaScript

js
const pre = document.querySelector("pre");
const classes = pre.classList;
const iterator = classes.values();

classes.forEach(function (value, key, listObj) {
  pre.textContent += `(${value} ${key})/${this}\n`;
}, "arg");

結果

規範

此特性似乎未在任何規範中定義。

瀏覽器相容性

另見