Ways to create a Set in JavaScript?

2019-03-09 05:53发布

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

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

var set = [];

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

8条回答
再贱就再见
2楼-- · 2019-03-09 06:42

Sets in ES6/ES2015:

ES6/ES2015 now has built in sets. A set is data structure which allows storage of unique values of any type, whether this are primitive values or object references. A set can be declared using the ES6 built in set constructor in the following manner:

const set = new Set([1, 2, 3, 4, 5]);

When creating a set using the Set constructor our newly created set object inherits from the Set.prototype. This has all sorts of auxiliary methods and properties. This allows you to easily do the following things:

Example:

const set = new Set([1, 2, 3, 4, 5]);

// checkout the size of the set
console.log('size is: ' + set.size);

// has method returns a boolean, true if the item is in the set
console.log(set.has(1));

// add a number
set.add(6);

// delete a number
set.delete(1);

// iterate over each element using a callback
set.forEach((el) => {
  console.log(el);
});

// remove all the entries from the set
set.clear();

Browser compatibility:

All major browser now fully support sets except IE where some features are missing. For exact reference please refer to the mdn docs.

查看更多
聊天终结者
3楼-- · 2019-03-09 06:42

You can try Buckets, is a javascript data structure library and has everything you need to manipulate sets.

查看更多
登录 后发表回答