要设置的 JavaScript 数组 [英] JavaScript Array to Set

查看:21
本文介绍了要设置的 JavaScript 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MSDN 引用了 JavaScript 的 Set 集合抽象.我有一个对象数组,我想将它们转换为一个集合,以便我能够按名称删除 (.delete()) 各种元素:

MSDN references JavaScript's Set collection abstraction. I've got an array of objects that I'd like to convert to a set so that I am able to remove (.delete()) various elements by name:

var array = [
    {name: "malcom", dogType: "four-legged"},
    {name: "peabody", dogType: "three-legged"},
    {name: "pablo", dogType: "two-legged"}
];

如何将此数组转换为集合?更具体地说,是否可以在不迭代上述数组的情况下执行此操作?文档相对缺乏(对于实例化集来说已经足够了;对于转换来说不够——如果可能的话).

How do I convert this array to a set? More specifically, is it possible to do this without iterating over the above array? The documentation is relatively lacking (sufficient for instantiated sets; not for conversions - if possible).

我可能也在考虑转换为 Map,用于按键删除.我想要完成的是一个可迭代的集合,可以通过主要通过键(而不是索引)访问元素来访问或修改它.

I may also be thinking of the conversion to a Map, for removal by key. What I am trying to accomplish is an iterable collection that can be accessed or modified via accessing the elements primarily via a key (as opposed to index).

从一个数组到另一个数组的转换是最终目标.

Conversion from an array to the other being the ultimate goal.

推荐答案

只需将数组传递给 Set 构造函数即可.Set 构造函数接受一个 iterable 参数.Array 对象实现了 iterable 协议,所以它是一个有效的参数.

Just pass the array to the Set constructor. The Set constructor accepts an iterable parameter. The Array object implements the iterable protocol, so its a valid parameter.

var arr = [55, 44, 65];
var set = new Set(arr);
console.log(set.size === arr.length);
console.log(set.has(65));

见这里

这篇关于要设置的 JavaScript 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆