将数组的所有值添加到 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:我知道两者都不起作用
原文由 Fuzzyma 发布,翻译遵循 CC BY-SA 4.0 许可协议
虽然
Set
API 仍然非常简单,您可以使用Array.prototype.forEach
并稍微缩短您的代码: