JavaScript: Set.prototype.forEach
New in JS2015.
setObj.forEach(f)
-
Apply function f to all values in set setObj.
Does not modify the set object.
Return undefined.
f is passed 3 arguments, x y z. The x is the current value in the set, y is the same as x, z is the set being iterated. The reason the first two arguments are the same is because to keep compatible in form with the forEach method of Array. setObj.forEach(f, thisArg)
-
Use thisArg for this Binding of f. If it is not given,
undefined
is used.
const s = new Set([3,4,5]); // apply a function to each value const t = s.forEach( (x => { console.log(x+10); return x+10; }) ); // prints // 13 // 14 // 15 // does not modify the variable console.log(s); // Set { 3, 4, 5 } // returns undefined console.log(t); // undefined
Here is example of 3 args form of f in forEach on a set object.
// 3 args form of f in forEach on a set object const s = new Set([3,4,5]); // apply a function to each value s.forEach( function (e, i, s) { console.log([e, i, s]); } ); // prints // [ 3, 3, Set { 3, 4, 5 } ] // [ 4, 4, Set { 3, 4, 5 } ] // [ 5, 5, Set { 3, 4, 5 } ]