开发者

Does Javascript supports Sets?

Does Javascript supports Sets(list w开发者_如何学Pythonith unique objects only) ?

I have found this link, but from what I remember foreach in JS in not supported by every browser.


Are your keys strings?

Every JavaScript object is a map, which means that it can represent a set.

As illustrated in the page you mentioned, each object will accept only one copy of each key (attribute name). The value for the key/attribute doesn't matter.


jshashtable would allow you to store any object as a key, and use the same pattern as in the link you gave. In addition it supplies a method to get an array of keys, which you can then iterate over. It also has good cross-browser support, so should fit nicely into any environment.


Now with ES6 (and polyfills/shims like corejs) you have them:

Set - JavaScript | MDN

Example:

var mySet = new Set([1, 2, 3, 2, 1]);  // => [1, 2, 3]
console.log(mySet.size);
console.log(mySet.has(3));
mySet.forEach(function(x){console.log(x)});

The Polifill is required since it is not supported by older browsers, so you can ignore it if you are aiming only at the latest ones.


You probably remember the Array.forEach() that is indeed not supported by older Opera and all IE browsers - the for (var x in ...) is part of the "native" JS as far as I know and is supported by all browsers.


JavaScript do support Set. Here is the link to canIuse website. It is supported by Chrome, Edge, Safari, Firefox, Opera and even IE. To declare set you can use Set() constructor.

let set = new Set();
set.add("John);

In this way you can use sets.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜