在JavaScript中创建Set的方法? [英] Ways to create a Set in JavaScript?

查看:105
本文介绍了在JavaScript中创建Set的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Eloquent JavaScript第4章中,通过创建对象并将值存储为属性名称,将任意值(例如,true)指定为属性值来创建一组值。要检查该值是否已包含在集合中,请使用运算符中的

In Eloquent JavaScript, Chapter 4, a set of values is created by creating an object and storing the values as property names, assigning arbitrary values (e.g. true) as property values. To check if the value is already contained in the set, the in operator is used:

var set = {};

if (!'Tom' in set) { 
  set.Tom = true;
}

这是惯用的JavaScript吗?不会更好地使用数组吗?

Is this idiomatic JavaScript? Wouldn't be using an array even better?

var set = [];

if (!'Tom' in set) { 
  set.push = 'Tom';
}


推荐答案

集合现在可用于ES2015(又名ES6,即ECMAScript 6)。自2015年6月以来,ES6一直是JavaScript的当前标准。

Sets are now available in ES2015 (aka ES6, i.e. ECMAScript 6). ES6 has been the current standard for JavaScript since June 2015.


ECMAScript 6具有适用于任意
值的数据结构Set ,快速并正确处理NaN。 - Axel Rauschmayer 探索ES6

来自 Axel Rauschmayer的书 探索ES6


管理单个元素:

Managing single elements:



> let set = new Set();
> set.add('red')

> set.has('red')
true
> set.delete('red')
true
> set.has('red')
false




确定Set的大小并清除它:

Determining the size of a Set and clearing it:



> let set = new Set();
> set.add('red')
> set.add('green')

> set.size
2
> set.clear();
> set.size
0

我会查看探索ES6 如果您想了解有关JavaScript中的集合的更多信息。这本书是免费在线阅读,但如果你想支持作者博士Axel Rauschmayer 你可以以30美元左右的价格购买这本书。

I would check out Exploring ES6 if you want to learn more about Sets in JavaScript. The book is free to read online, but if you would like to support the author Dr. Axel Rauschmayer you can purchase the book for around $30.

如果你现在想使用套装和ES6你可以使用 Babel ,ES6到ES5的转换器及其polyfills。

If you want to use Sets and ES6 now you can use Babel, the ES6 to ES5 transpiler, and its polyfills.

编辑:截至6月6日, 2017年大多数主流浏览器在其最新版本(IE 11除外)中都有完整的Set支持。这意味着如果您不关心支持旧版浏览器,则可能不需要使用babel。如果您想查看包括当前浏览器在内的不同浏览器的兼容性,请查看 Kangax的ES6兼容性表

As of June 6th, 2017 most of the major browsers have full Set support in their latest versions (except IE 11). This means you may not need babel if you don't care to support older browsers. If you want to see compatibility in different browsers including your current browser check Kangax's ES6 compatibility table.

这篇关于在JavaScript中创建Set的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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