如何将值数组添加到集合

Fuz*_*yma 20 javascript 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)
}
Run Code Online (Sandbox Code Playgroud)

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

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

WiR*_*R3D 23

这是IMO最优雅的

// for a new Set 
const x = new Set([1,2,3,4]);

// for an existing Set
const y = new Set();

[1,2,3,4].forEach(y.add, y);
Run Code Online (Sandbox Code Playgroud)

  • @RyanShillington 不是真的,过去是这样,但自从发布答案以来浏览器已经优化了很多。参见 https://jsben.ch/fxaYy(感谢@Redu) (8认同)
  • forEach 比遍历数组慢约 200 倍。对于一些值来说这很好,但要注意这是否是您一直在做的事情。/sf/ask/3067523161/ (2认同)
  • @WiR3D 好吧,天哪。这是一个很棒的消息。 (2认同)

ama*_*kkg 16

尽管SetAPI仍然非常简单,但是您可以使用Array.prototype.forEach和缩短代码:

array.forEach(item => mySet.add(item))
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢“糟糕的 API”被称为“简约”! (31认同)
  • @ed22 请参阅 [forEach 文档](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach): `thisArg` (可选) - 用作 `this 的值` 执行_callback_时 (5认同)
  • 我认为这并不比“for of”循环更好。尤其是第二个更令人困惑。 (4认同)
  • @amankkg我永远不会习惯 mySet.add 不使用点之前对象的上下文,而是像一个完全独立的方法。 (4认同)
  • 为什么我们需要第二个参数: array.forEach(mySet.add, mySet) ? (3认同)

Jul*_*ien 13

这是一种实用的方法,返回一个新集合:

const set = new Set(['a', 'b', 'c'])
const arr = ['d', 'e', 'f']
const extendedSet = new Set([ ...set, ...arr ])
// Set { 'a', 'b', 'c', 'd', 'e', 'f' }
Run Code Online (Sandbox Code Playgroud)

  • @PauloNeves 听起来你没有使用扩展语法“...” (12认同)

cla*_*rez 7

如何使用扩展运算符轻松地将新数组项混合到现有集合中?

const mySet = new Set([1,2,3,4])
const additionalSet = [5,6,7,8,9]
mySet = new Set([...mySet, ...additionalSet])
Run Code Online (Sandbox Code Playgroud)

JSFIDDLE

  • 再一次:“显然你没有阅读代码中的注释,我在其中指出该集合是在其他地方创建的,并且我无法创建新的集合” (5认同)
  • 将“const”mySet 更改为“let” (3认同)

JHH*_*JHH 5

您还可以使用Array.reduce()

const mySet = new Set();
mySet.add(42); // Just to illustrate that an existing Set is used

[1, 2, 3].reduce((s, e) => s.add(e), mySet);
Run Code Online (Sandbox Code Playgroud)

  • 当您需要的只是“forEach”的迭代时,使用“reduce”在这里没有意义。请参阅@WiR3D 的回答。 (19认同)
  • foreach 不是一个表达式,另一方面,reduce 是一个表达式,因此您可以一次性返回和减少。 (4认同)
  • 我真的不明白你的反对意见。有时您需要单语句解决方案,例如在不需要花括号块的 lambda 中,或者在初始化中。虽然“reduce”可能不是最明显的选择,但我不明白它为什么不“有意义”——你将一个数组减少为其他东西——一个集合——这正是“reduce”的目的。 (2认同)
  • @JHH 要点是 `[1, 2, 3].forEach(e => mySet.add(e))` 或 `for (const e of [1, 2, 3]) mySet.add(e)`会更有意义。 (2认同)

mon*_*lof 5

创建一个新集合:

    //Existing Set
    let mySet = new Set([1,2,3,4,5]);
    //Existing Array
    let array = [6,7,8,9,0];
        
    mySet = new Set(array.concat([...mySet]));
    console.log([...mySet]);
    
    //or single line
    console.log([...new Set([6,7,8,9,0].concat([...new Set([1,2,3,4,5])]))]);
Run Code Online (Sandbox Code Playgroud)


hyg*_*ull -4

@Fuzzyma,我建议您使用JavaScript原型来定义Set上的新方法。

不要使用Set上定义的内置方法名称。

如果您仍然喜欢使用与内置函数名称相同的函数名称,add那么更好的方法是继承Set并重写add()方法。

这是向现有对象添加方法而不影响其方法并使用我们自己的同名方法的更好方法。方法重写的魅力,一个很好的 OOP 概念。

在下面的代码中,我定义addItems()Set

请访问http://rextester.com/LGPQC98007在线尝试。

var arr = [3, 7, 8, 75, 65, 32, 98, 32, 3];
var array = [100, 3, 200, 98, 65, 300]; 

// Create a Set
var mySet = new Set(arr);
console.log(mySet);

// Adding items of array to mySet
Set.prototype.addItems = function(array) {
    for(var item of array){
        this.add(item)
    }
}

mySet.addItems(array);
console.log(mySet)
Run Code Online (Sandbox Code Playgroud)

“ 输出

Set { 3, 7, 8, 75, 65, 32, 98 }
Set { 3, 7, 8, 75, 65, 32, 98, 100, 200, 300 }
Run Code Online (Sandbox Code Playgroud)

  • 您可能想看看[为什么扩展本机对象是一种不好的做法?](/sf/ask/982392631/)。此外,如果您使用较少的格式,您的答案(和评论)将更具可读性。最后,Stack Overflow 有一个称为 Stack Snippets 的功能。在编辑器中,您可以单击带有尖括号 (`<>`) 的按钮并将 JavaScript 代码粘贴到其中。这将使它可供其他人运行。 (3认同)