--- title: Set.prototype.forEach() slug: Web/JavaScript/Reference/Global_Objects/Set/forEach translation_of: Web/JavaScript/Reference/Global_Objects/Set/forEach ---
forEach
方法会根据集合中元素的插入顺序,依次执行提供的回调函数。
mySet.forEach(callback[, thisArg])
callback
currentValue
, currentKey{{optional_inline}}
set{{optional_inline}}
forEach
方法的集合对象thisArg
{{optional_inline}}
this
值。{{jsxref("undefined")}}.
forEach
方法会依次为集合中的元素执行回调函数,就算元素的值是 undefined
。
回调函数有三个参数:
但是由于集合对象中没有索引(keys),所以前两个参数都是{{domxref("Set")}}中元素的值(values),之所以这样设计回调函数是为了和{{jsxref("Map.foreach", "Map")}} 以及{{jsxref("Array.forEach","Array")}}的 forEach
函数用法保持一致。
如果提供了一个 thisArg
参数给 forEach
函数,则参数将会作为回调函数中的 this
值。否则 this
值为 undefined
。回调函数中 this
的绑定是根据函数被调用时通用的 this
绑定规则来决定的。
forEach
函数为集合对象中每个元素都执行一次回调;它不会返回任何值。
以下代码依次打印集合对象的元素:
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 |
---|---|---|
{{SpecName('ES6', '#sec-set.prototype.foreach', 'Set.prototype.forEach')}} | {{Spec2('ES6')}} | Initial definition. |