MDN’s new design is in Beta! A sneak peek:


该新特性属于 ECMAScript 2015(ES6)规范,在使用时请注意浏览器兼容性。

forEach 方法根据集合中元素的顺序,对每个元素都执行提供的 callback 函数一次。


mySet.forEach(callback[, thisArg])




这个forEach方法会针对集合中的每个元素执行提供的callback函数一次。 对于那些已经被删除的元素,它是不会执行的,但是,对于元素是undefined的情况则相反。

callback 有三个参数:

  • 元素的值
  • 元素的索引
  • 将要遍历的集合对象

The are no keys in Set objects. However, the first two arguments are both values contained in the Set, so that the callback function is consistent with the forEach methods for Map and Array.

If a thisArg parameter is provided to forEach, it will be passed to callback when invoked, for use as its this value.  Otherwise, the value undefined will be passed for use as its this value.  The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

The range of elements processed by forEach is set before the first invocation of callback. Elements which are added to the Set object after the call to forEach begins, will not be visited by callback. If existing elements of the Set object are changed, or deleted, their value as passed to callback will be the value at the time forEach visits them; elements that are deleted are not visited.

forEach executes the callback function once for each element in the Set object; it does not return a value.


Logging the contents of a Set object

The following code logs a line for each element in an Set object:

function logSetElements(value1, value2, set) {
    console.log("s[" + value1 + "] = " + value2);

new Set(["foo", "bar", undefined]).forEach(logSetElements);

// logs:
// "s[foo] = foo"
// "s[bar] = bar"
// "s[undefined] = undefined"


Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
Standard Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 38 25.0 (25.0) 11 25 7.1
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 未实现 38 25.0 (25.0) 未实现 未实现 8

See also


 此页面的贡献者: tommyzqfeng, timlee1128, 201341, gaigeshen
 最后编辑者: tommyzqfeng,