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

句法

tokenList.forEach(callback [, thisArg]);
					

参数

callback
Function to execute for each element, eventually taking three arguments:
currentValue

The current element being processed in the array.

currentIndex

The index of the current element being processed in the array.

listObj
The array that forEach() is being applied to.
thisArg 可选
Value to use as this when executing callback .

返回值

undefined .

范例

In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList 使用 Element.classList . We when retrieve an iterator containing the values using forEach() , writing each one to the <span> 's Node.textContent forEach() inner function.

HTML

<span class="a b c"></span>
								

JavaScript

let span = document.querySelector("span");
let classes = span.classList;
let iterator = classes.values();
classes.forEach(
  function(value, key, listObj) {
    span.textContent += `${value} ${key}/${this}  ++  `;
  },
  "arg"
);
								

结果

Polyfill

This polyfill adds compatibility to all Browsers supporting ES5 :

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

规范

规范 状态 注释
DOM
The definition of 'forEach() (as iterable<Node>)' in that specification.
实时标准 初始定义。

浏览器兼容性

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 45 Edge 16 Firefox 50 IE 不支持 No Opera 32 Safari 10 WebView Android 45 Chrome Android 45 Firefox Android 50 Opera Android 32 Safari iOS 10 Samsung Internet Android 5.0

图例

完整支持

完整支持

不支持

不支持

另请参阅

元数据

  • 最后修改: