Javascript 如何将一组值添加到 Set
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50881453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add an array of values to a Set
提问by Fuzzyma
The old school way of adding all values of an array into the Set is:
将数组的所有值添加到 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)
}
Is there a more elegant way of doing this? Maybe mySet.add(array)or mySet.add(...array)?
有没有更优雅的方法来做到这一点?也许mySet.add(array)或mySet.add(...array)?
PS: I know both do not work
PS:我知道两者都不起作用
回答by amankkg
While SetAPI is still very minimalistic, you can use Array.prototype.forEachand shorten your code a bit:
虽然SetAPI 仍然非常简约,但您可以使用Array.prototype.forEach并稍微缩短代码:
array.forEach(item => mySet.add(item))
// alternative, without anonymous arrow function
array.forEach(mySet.add, mySet)
回答by Julien
Here's a functional way, returning a new set:
这是一种功能方式,返回一个新集合:
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' }
回答by WiR3D
This is IMO the most elegant
这是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);
回答by montelof
create a new Set:
创建一个新集合:
//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])]))]);
回答by JHH
You can also use Array.reduce():
您还可以使用Array.reduce():
const mySet = new Set();
mySet.add(42);
[1, 2, 3].reduce((s, e) => s.add(e), mySet);
回答by Thomas-Louis Simard
Just post that here for inspiration .. Creating a class that extends Set, and add a addRange method.
只需在此处发布以获取灵感.. 创建一个扩展 Set 的类,并添加一个 addRange 方法。
class MegaSet extends Set {
constructor(iterable) {
super(iterable);
}
addRange(range) {
for (var elem of range) {
this.add(elem);
}
}
}
const array = [1,2,3,5,5,6];
let mySet = new MegaSet([1,2,3,4]);
mySet.addRange(array);
console.log([...mySet]);
回答by clayperez
回答by baao
There's currently no addAllmethod for Sets, but you have two options to simplify your life when working with them. The first one would be to extend the prototype. Before you do that, read this postand decide afterwards if the possible consequences are ok for your project/intended use.
目前没有addAll使用 Set 的方法,但是在使用它们时,您有两种选择可以简化您的生活。第一个是扩展原型。在您这样做之前,请阅读这篇文章,然后再决定可能的后果是否适合您的项目/预期用途。
if (!Set.prototype.addAll) {
Set.prototype.addAll = function(items) {
if (!Array.isArray(items)) throw new TypeError('passed item is not an array');
// or (not sure what the real Set.prototype will get sometime)
// if (!Array.isArray(items)) items = [items];
for (let it of items) {
this.add(it);
}
return this;
}
}
If you decided not to extend the prototype, just create a function that you can reuse in your project
如果您决定不扩展原型,只需创建一个可以在项目中重用的函数
function addAll(_set, items) {
// check set and items
for (let it of items) {
_set.add(it);
}
return _set;
}
回答by hygull
@Fuzzyma, I'll suggest you to use Prototypingof JavaScript to define new method on Set.
@Fuzzyma,我建议您使用JavaScript原型来定义Set上的新方法。
Do not use in-built method name defined on Set.
If you still prefer to use the same function name as in-built function name like
addthen the better approach would be to inherit the Setand overrideadd()method.This is better way to add methods to existing objects without affecting their methods and use our own methods with same name. The charisma of Method overriding, a nice OOP concept.
不要使用在Set 上定义的内置方法名称。
如果您仍然喜欢使用与内置函数名称相同的函数名称,
add那么更好的方法是继承Set和 overrideadd()方法。这是向现有对象添加方法而不影响它们的方法并使用我们自己的同名方法的更好方法。Method overriding的魅力,一个很好的 OOP 概念。
Here in the below code, I have defined addItems()on Set.
在下面的代码中,我定义addItems()了Set。
Try it online at 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)
» Output
“ 输出
Set { 3, 7, 8, 75, 65, 32, 98 }
Set { 3, 7, 8, 75, 65, 32, 98, 100, 200, 300 }

