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

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

问题描述

MSDN引用JavaScript的集合抽象。我有对象的数组,我想,这样我可以按名称删除( .delete())的各种元素转换为一组:

  VAR阵列= [
    {狗:鲍勃,猫:施舍},
    {小狗说:先生,猫:皮博迪},
    {狗:darkwing猫:鸭}
];

我怎么这个数组转换为一组?更具体地说,是有可能做到这一点没有遍历数组之上?该文档是比较欠缺的(足够的实例化的集合,而不是转化 - 如果可能的话)。

我也可能会想转换到的地图,通过关键的去除。我试图实现是一个可迭代集合,可以经由主要通过一个关键访问单元进行访问或修改(相对于索引)。

从阵列到另一个是终极目标转换。


解决方案

只是通过数组设置构造函数。设置构造函数接受一个迭代参数。数组对象实现了迭代的协议,因此它的一个有效参数。

\r
\r

VAR ARR = [55,44,65]。\r
VAR套=新集(ARR);\r
的console.log(set.size === arr.length);\r
的console.log(set.has(65));

\r

\r
\r

看到这里

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 = [
    {dog: "bob", cat: "dole"},
    {dog: "mr.", cat: "peabody"},
    {dog: "darkwing", cat: "duck"}
];

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).

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.

解决方案

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));

See here

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

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