Set

Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

El objeto Set te permite almacenar valores únicos de cualquier tipo, incluso valores primitivos u objetos de referencia.

Sintaxis

new Set([iterable]);

Parámetros

iterable
Si un objeto iterable es pasado, todos sus elementos serán añadidos a un new Set. null es tratado como undefined.

Descripción

Los objetos Set son colecciones de valores, tú puedes iterar sus elementos en el orden de su insercción. Un valor en un objeto Set sólo puede estar una vez; éste es unico en la colección Set.

Value equality

Because each value in the Set has to be unique, the value equality will be checked and is not based on the same algorithm as the one used in the === operator. Specifically, for Sets, +0 (which is strictly equal to -0) and -0 are different values. However, this has been changed in the latest ECMAScript 6 specification. Starting with Gecko 29.0 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26) (bug 952870) and a recent nightly Chrome, +0 and -0 are treated as the same value in Set objects. Also, NaN and undefined can also be stored in a Set. NaN is considered the same as NaN (even though NaN !== NaN).

Propiedades

Set.length
El valor de la propiedad length es 0.
get Set[@@species]
La función constructora es usada para crear objetos derivados.
Set.prototype
Representa el prototipo del constructor Set. Permite la addición de propiedades a todos los objetos Set.

Instancias Set

Todas las instancias de Set heredan de Set.prototype.

Propiedades

Set.prototype.constructor
Returns the function that created an instance's prototype. This is the Set function by default.
Set.prototype.size
Returns the number of values in the Set object.

Métodos

Set.prototype.add(value)
Appends a new element with the given value to the Set object. Returns the Set object.
Set.prototype.clear()
Removes all elements from the Set object.
Set.prototype.delete(value)
Removes the element associated to the value and returns the value that Set.prototype.has(value) would have previously returned. Set.prototype.has(value) will return false afterwards.
Set.prototype.entries()
Returns a new Iterator object that contains an array of [value, value] for each element in the Set object, in insertion order. This is kept similar to the Map object, so that each entry has the same value for its key and value here.
Set.prototype.forEach(callbackFn[, thisArg])
Calls callbackFn once for each value present in the Set object, in insertion order. If a thisArg parameter is provided to forEach, it will be used as the this value for each callback.
Set.prototype.has(value)
Returns a boolean asserting whether an element is present with the given value in the Set object or not.
Set.prototype.keys()
Is the same function as the values() function and returns a new Iterator object that contains the values for each element in the Set object in insertion order.
Set.prototype.values()
Returns a new Iterator object that contains the values for each element in the Set object in insertion order.
Set.prototype[@@iterator]()
Returns a new Iterator object that contains the values for each element in the Set object in insertion order.

Ejemplos

Usando el objeto Set

var mySet = new Set();

mySet.add(1);
mySet.add(5);
mySet.add("some text");
var o = {a: 1, b: 2};
mySet.add(o);

mySet.has(1); // true
mySet.has(3); // false, 3 no ha sido añadido al Set
mySet.has(5);              // true
mySet.has(Math.sqrt(25));  // true
mySet.has("Some Text".toLowerCase()); // true
mySet.has(o); // true

mySet.size; // 4

mySet.delete(5); // Elimina 5 del Set
mySet.has(5);    // false, 5 fue eliminado

mySet.size; // 3, sólo removimos un valor

Iterando los Sets

// iterate over items in set
// logs the items in the order: 1, "some text" 
for (let item of mySet) console.log(item);

// logs the items in the order: 1, "some text" 
for (let item of mySet.keys()) console.log(item);
 
// logs the items in the order: 1, "some text" 
for (let item of mySet.values()) console.log(item);

// logs the items in the order: 1, "some text" 
//(key and value are the same here)
for (let [key, value] of mySet.entries()) console.log(key);

// convert set to plain Array (with Array comprehensions)
var myArr = [v for (v of mySet)]; // [1, "some text"]
// Alternative (with Array.from)
var myArr = Array.from(mySet); // [1, "some text"]

// the following will also work if run in an HTML document
mySet.add(document.body);
mySet.has(document.querySelector("body")); // true

// converting between Set and Array
mySet2 = new Set([1,2,3,4]);
mySet2.size; // 4
[...mySet2]; // [1,2,3,4]

// intersect can be simulated via  
var intersection = new Set([x for (x of set1) if (set2.has(x))]);

// Iterate set entries with forEach
mySet.forEach(function(value) {
  console.log(value);
});

// 1
// 2
// 3
// 4

Relación con los objetos Array

var myArray = ["value1", "value2", "value3"];

// Use the regular Set constructor to transform an Array into a Set
var mySet = new Set(myArray);

mySet.has("value1"); // returns true

// Use the spread operator to transform a set into an Array.
console.log(uneval([...mySet])); // Will show you exactly the same Array as myArray

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Set' in that specification.
Standard Initial definition.
ECMAScript 2016 Draft (7th Edition, ECMA-262)
The definition of 'Set' in that specification.
Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support

38 [1]

13 (13) 11 25 7.1
Constructor argument: new Set(iterable) 38 13 (13) No support 25 No support
iterable 38 17 (17) No support 25 7.1
Set.clear() 38 19 (19) 11 25 7.1
Set.keys(), Set.values(), Set.entries() 38 24 (24) No support 25 7.1
Set.forEach() 38 25 (25) 11 25 7.1
Value equality for -0 and 0 38 29 (29) No support 25 No support
Constructor argument: new Set(null) (Yes) 37 (37) ? ? ?
Monkey-patched add() in Constructor (Yes) 37 (37) ? ? ?
Set[@@species] ? 41 (41) ? ? ?
Set() without new throws ? 42 (42) ? ? ?
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support No support 38 [1] 13.0 (13) No support No support 8
Constructor argument: new Set(iterable) No support 38 13.0 (13) No support No support No support
iterable No support No support 17.0 (17) No support No support 8
Set.clear() No support 38 19.0 (19) No support No support 8
Set.keys(), Set.values(), Set.entries() No support 38 24.0 (24) No support No support 8
Set.forEach() No support 38 25.0 (25) No support No support 8
Value equality for -0 and 0 No support 38 29.0 (29) No support No support No support
Constructor argument: new Set(null) ? (Yes) 37.0 (37) ? ? ?
Monkey-patched add() in Constructor ? (Yes) 37.0 (37) ? ? ?
Set[@@species] ? ? 41.0 (41) ? ? ?
Set() without new throws ? ? 42.0 (42) ? ? ?

[1] The feature was available behind a preference from Chrome 31. In chrome://flags, activate the entry “Enable Experimental JavaScript”.

See also

Etiquetas y colaboradores del documento

 Colaboradores en esta página: Chofoteddy
 Última actualización por: Chofoteddy,