将数组的所有值添加到Set中的传统方法是:

// for the sake of this example imagine this set was created somewhere else
// and I cannot construct a new one out of an array
let mySet = new Set()

for(let item of array) {
  mySet.add(item)
}

有没有更优雅的方式做到这一点?也许mySet.add(array)mySet.add(...array)

PS:我知道两者都不起作用

最佳答案

尽管Set API仍然非常简单,但是您可以使用 Array.prototype.forEach 并缩短代码一些:

array.forEach(item => mySet.add(item))

// alternative, without anonymous arrow function
array.forEach(mySet.add, mySet)

09-30 13:51
查看更多