将数组的所有值添加到集合中的传统方法是:
// 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)
ama*_*kkg 16
尽管SetAPI仍然非常简单,但是您可以使用Array.prototype.forEach和缩短代码:
array.forEach(item => mySet.add(item))
Run Code Online (Sandbox Code Playgroud)
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)
如何使用扩展运算符轻松地将新数组项混合到现有集合中?
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)
您还可以使用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)
创建一个新集合:
//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。
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)