Does Javascript supports Sets(list with unique objects only) ?
I have found this link, but from what I remember foreach in JS in not supported by every browser.
Does Javascript supports Sets(list with 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.
HashSet
wrapper available to download with jshashtable: code.google.com/p/jshashtable/downloads/… –
Municipality Now with ES6 (and polyfills/shims like corejs) you have them:
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.
© 2022 - 2024 — McMap. All rights reserved.