A
O Set is a object that allows setar values.You can start a Set empty, or start already with some content from the builder:let foo = new Set([1, 2, 3, 4, 5]);
foo.add(6);
console.log(foo.entries());
You will return:SetIterator {1, 2, 3, 4, 5, 6}
Iterating a SetO .entries can be used in one for to iterate, just as you can use the method .forEach of the Set, so://O primeiro e o segundo argumento tem o mesmo valor
//o terceiro retorna o Set atual, pode ser interessante se usar a função para diferentes Sets
foo.forEach(function (valor1, valor2, currentSet) {
console.log('set[' + chave + '] = ' + valor);
console.log(currentSet); //Exibe o Set atual
});
Note that forEach has a second argument:.forEach(callback [, thisArg])
In place of thisArg you can put something else so that the this inside the callback is what you defined, how it might be this of the above scope, example:let foo = new Set([1, 2, 3, 4, 5]);
document.querySelector("#test").onclick = function () {
foo.forEach(function (v1, v2, thisArg) {
console.log(v1, v2, this);
}, this);
};<button id="test">Testar</button>Another way to iterate is to use own Set directly inside one for...of (or) for...in, although this second has no advantage, since we only care about the value:for (let valor of foo) {
console.log(valor);
}
I think this way it gets even cleaner than use .entries or .forEach, the advantage of .forEach even would be the use of callbacks dinamics, then instead of writing three lines like this:for (let valor of foo) {
meuCallback(valor);
}
You would only write one like this:foo.forEach(meuCallback);
Then you can use for...of when it's just iterating and forEach when you have dinamic callbacks.Support for SetAccording to the MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/forEach The browsers that support are:Chrome 38+12+IE 11+ (miraculously this I did not expect)Safari 8+Firefox 25+If you have no support in all browsers, is there any Polyfill?I'm going to be honest, and understand this as a personal opinion, Polyfill for this seems a little overkill, it's serious, as the purpose is to create unic values a simple check with Array.indexOf would already solve before adding to an Array something, for example:var x = [1,2,3];
//Supondo que este if seja executado por um callback e que os dados sejam dinamicos
var novo = 3;
if (x.indexOf(novo) === -1) {
x.push(novo);
} else {
console.log('Já adicionado');
}
But if you think you're going to use this in a lot of stuff even maybe a polyfill is util. As soon as I test the polyfills cited in the comments well and make sure they work well I will add here (I do not usually add something that has not tested at least once).Converting to Array or argumentsTo convert to array can use the three points (this is called Spread syntax and this No is supported in Internet Explorer), so:let foo = new Set([1, 2, 3, 4, 5]);
let arr = [...foo];
console.log(arr);Or can pass to arguments of such a functionlet foo = new Set([1, 2, 3, 4, 5]);
teste1(...foo);
teste2(...foo);
//Especificos
function teste1(a, b, c, d) {
console.log("test1:", a, b, c, d);
}
//usando "arguments"
function teste2() {
console.log("test2:", arguments);
}Spread Support:Chrome 46+12+Firefox 16+Safari 8+Another way is by using Array.from:Array.from(foo);
Support:Chrome 45+Edge (apparently all versions)Firefox 32+Safari 9+Details on the SetWhat are the values I can add to a Set object?Anything even that could add to a variable or array, it works as an array itself, but simply has the detail of the control of unic valuesCan I have a string and int collection in the same Set object?Yeah, you can stand anything, you can even have Set inside Set, but one thing needs to be clear, the added subitet values of Objects are as references, i.e. the value is not copied it is referenced, this in Arrays and Object too, because this is how JavaScript is, of course you can copy/clonate an entire object, but this is another story.What is the criterion for determining whether an element already belongs to the Set object?You can use .has, it is worth noting that it is as I said, it is all as reference, for example:var a = {};
var b = {};
console.log(a === b); //Retorna FALSEAlthough similar are different objects, then when doing this:var a = {};
var meuSet = new Set;
meuSet.add(a);
console.log(meuSet.has({})); //Retorna FALSE
console.log(meuSet.has(a)); //Retorna TRUEO meuSet.has(a) returns TRUE because this checking the object referred to in the variable a, this doesn't have to Set, but how JavaScript works (such behavior is similar in many languages)