有没有办法在迭代中修改Set数据结构(ECMAScript 6)?

les*_*ang 1 ecmascript-6

SetES6中的对象有一个forEach方法,就像Array对象一样.有没有办法在Set使用该forEach方法迭代对象时修改值?

例如:

// Array object in ES5 can be modified in iteration
var array = [1, 2, 3];
array.forEach(function(int, idx, a) {
    a[idx] = int * int;
});
array;  // => [1, 4, 9]
Run Code Online (Sandbox Code Playgroud)

但是当迭代Set对象时,

// Set will not be updated
var set = new Set([1, 2, 3]);
set.forEach(function(val1, val2, s) {
    val2 = val1 * val1;
})
set;   // => [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

有没有办法达到与Array对象相同的效果?

log*_*yth 5

我可能会这样做

var set = new Set([1, 2, 3]);
set = new Set(Array.from(set, val => val * val));
Run Code Online (Sandbox Code Playgroud)

只使用新值创建一个新集合,并替换旧值.在迭代它时改变集合是一个坏主意,似乎在您的用例中很容易避免.