如何将一组值添加到集合

新手上路,请多包涵

将数组的所有值添加到 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 许可协议

阅读 258
1 个回答

虽然 Set API 仍然非常简单,您可以使用 Array.prototype.forEach 并稍微缩短您的代码:

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

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

原文由 amankkg 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题