aboutsummaryrefslogtreecommitdiff
path: root/files/es/web/javascript/reference/global_objects/set/index.html
diff options
context:
space:
mode:
Diffstat (limited to 'files/es/web/javascript/reference/global_objects/set/index.html')
-rw-r--r--files/es/web/javascript/reference/global_objects/set/index.html230
1 files changed, 230 insertions, 0 deletions
diff --git a/files/es/web/javascript/reference/global_objects/set/index.html b/files/es/web/javascript/reference/global_objects/set/index.html
new file mode 100644
index 0000000000..db091b3a59
--- /dev/null
+++ b/files/es/web/javascript/reference/global_objects/set/index.html
@@ -0,0 +1,230 @@
+---
+title: Set
+slug: Web/JavaScript/Referencia/Objetos_globales/Set
+tags:
+ - ECMAScript 2015
+ - JavaScript
+ - Object
+ - set
+translation_of: Web/JavaScript/Reference/Global_Objects/Set
+---
+<div>{{JSRef}}</div>
+
+<p>El objeto <strong><code>Set</code></strong> permite almacenar valores únicos de cualquier tipo, incluso {{Glossary("Primitive", "valores primitivos")}} u referencias a objetos.</p>
+
+<h2 id="Sintaxis">Sintaxis</h2>
+
+<pre class="syntaxbox">new Set([iterable]);</pre>
+
+<h3 id="Parámetros">Parámetros</h3>
+
+<dl>
+ <dt>iterable</dt>
+ <dd>Si un <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">objeto iterable </a>es pasado, todos sus elementos serán añadidos al nuevo Set. Si no se especifica este parámetro, o si su valor es <code>null,</code> el nuevo <code>Set</code> estará vacío.</dd>
+</dl>
+
+<h3 id="Valor_retornado">Valor retornado</h3>
+
+<p>Una nueva instancia de <code>Set</code>.</p>
+
+<h2 id="Descripción">Descripción</h2>
+
+<p>Los objetos <code><strong>Set</strong></code> son colecciones de valores. Se puede iterar sus elementos en el orden de su inserción. Un valor en un <code>Set</code> <strong>sólo puede estar una vez</strong>; éste es único en la colección <code>Set</code>.</p>
+
+<h3 id="Igualdad_de_valores">Igualdad de valores</h3>
+
+<p>Ya que cada valor en el Set tiene que ser único, la igualdad del valor será comprobada y esta igualdad no se basa en el mismo algoritmo usado en el operador <code>===</code>. Específicamente, para Sets, <code>+0</code> (el cual es estrictamente igual a <code>-0</code>) y <code>-0</code> son valores distintos. Sin embargo, esto ha cambiado en la última especificación ECMAScript 6. Iniciando con Gecko 29.0 {{geckoRelease("29")}} ({{bug("952870")}}) y un <a href="https://code.google.com/p/v8/issues/detail?id=3069">recent nightly Chrome</a>, <code>+0</code> y <code>-0</code> son tratados como el mismo valor en objetos <code>Set</code>. </p>
+
+<p><code>NaN</code> y <code>undefined</code> también pueden ser almacenados en un Set. <code>NaN</code> es considerado igual que <code>NaN</code> (A pesar que <code>NaN !== NaN</code>).</p>
+
+<h2 id="Propiedades">Propiedades</h2>
+
+<dl>
+ <dt><code>Set.length</code></dt>
+ <dd>El valor de la propiedad <code>length</code> es 0.</dd>
+ <dt>{{jsxref("Set.@@species", "get Set[@@species]")}}</dt>
+ <dd>La función constructora que es usada para crear objetos derivados.</dd>
+ <dt>{{jsxref("Set.prototype")}}</dt>
+ <dd>Representa el prototipo para el constructor Set. Permite la adición de propiedades a todos los objetos Set.</dd>
+</dl>
+
+<h2 id="Instancias_Set">Instancias <code>Set</code></h2>
+
+<p>Todas las instancias de <code>Set</code> heredan de {{jsxref("Set.prototype")}}.</p>
+
+<h3 id="Propiedades_2">Propiedades</h3>
+
+<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Set/prototype','Properties')}}</p>
+
+<h3 id="Métodos">Métodos</h3>
+
+<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Set/prototype','Methods')}}</p>
+
+<h2 id="Ejemplos">Ejemplos</h2>
+
+<h3 id="Usando_el_objeto_Set">Usando el objeto <code>Set</code></h3>
+
+<pre class="brush: js">const mySet = new Set();
+
+mySet.add(1);
+mySet.add(5);
+mySet.add('some text');
+
+const o = {a: 1, b: 2};
+mySet.add(o);
+
+<code>mySet.add({a: 1, b: 2}); // La variable "o" referencia a otro objeto, por lo que agrega otro valor.
+</code>
+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; // 5
+
+mySet.delete(5); // Elimina 5 del Set
+mySet.has(5); // false, 5 fue eliminado
+
+mySet.size; // 4, sólo removimos un valor
+<code>console.log(mySet);// Set {1, "some text", Object {a: 1, b: 2}, Object {a: 1, b: 2}}</code></pre>
+
+<h3 id="Iterando_los_Sets">Iterando los Sets</h3>
+
+<pre class="brush: js">// iterar todos los items de un set
+// imprimir en consola los items en orden: 1, 'some text', {a: 1, b: 2}
+for (let item of mySet) console.log(item);
+
+// imprimir en consola los items en orden: 1, 'some text', {a: 1, b: 2}
+for (let item of mySet.keys()) console.log(item);
+
+// imprimir en consola los items en orden: 1, 'some text', {a: 1, b: 2}
+for (let item of mySet.values()) console.log(item);
+
+// imprimir en consola los items en orden: 1, 'some text', {a: 1, b: 2}
+//(key y value poseen en mismo valor en este caso)
+for (let [key, value] of mySet.entries()) console.log(key);
+
+// crear un Array plano con los mismos valores, utilizando Array.from
+const myArr = Array.from(mySet); // [1, 'some text', {a: 1, b: 2}]
+
+// también se puede utilizar para guardar elementos del DOM
+mySet.add(document.body);
+mySet.has(document.querySelector('body')); // true
+
+// crear un Array plano con los mismos valores, utilizando propagación
+const mySet2 = new Set([1,2,3,4]);
+mySet2.size; // 4
+[...mySet2]; // [1,2,3,4]
+
+// la intersección entre dos sets puede ser simulada con
+const intersection = <code>new Set([...set1].filter(x =&gt; set2.has(x)));</code>
+
+<code>// la diferencia puede ser simulada con
+const difference = new Set([...set1].filter(x =&gt; !set2.has(x)));</code>
+
+// Iteración utilizando forEach
+mySet.forEach((value) =&gt; {
+ console.log(value);
+});
+
+// 1
+// 2
+// 3
+// 4</pre>
+
+<h3 id="Implementando_operaciones_básicas">Implementando operaciones básicas</h3>
+
+<pre class="brush: js line-numbers language-js"><code class="language-js">Set<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>isSuperset <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>subset<span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ <span class="keyword token">for</span> <span class="punctuation token">(</span><span class="keyword token">var</span> elem <span class="keyword token">of</span> subset<span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ <span class="keyword token">if</span> <span class="punctuation token">(</span><span class="operator token">!</span><span class="keyword token">this</span><span class="punctuation token">.</span><span class="function token">has</span><span class="punctuation token">(</span>elem<span class="punctuation token">)</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ <span class="keyword token">return</span> <span class="keyword token">false</span><span class="punctuation token">;</span>
+ <span class="punctuation token">}</span>
+ <span class="punctuation token">}</span>
+ <span class="keyword token">return</span> <span class="keyword token">true</span><span class="punctuation token">;</span>
+<span class="punctuation token">}</span>
+
+Set<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>union <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>setB<span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ <span class="keyword token">var</span> union <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Set</span><span class="punctuation token">(</span><span class="keyword token">this</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
+ <span class="keyword token">for</span> <span class="punctuation token">(</span><span class="keyword token">var</span> elem <span class="keyword token">of</span> setB<span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ union<span class="punctuation token">.</span><span class="function token">add</span><span class="punctuation token">(</span>elem<span class="punctuation token">)</span><span class="punctuation token">;</span>
+ <span class="punctuation token">}</span>
+ <span class="keyword token">return</span> union<span class="punctuation token">;</span>
+<span class="punctuation token">}</span>
+
+Set<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>intersection <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>setB<span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ <span class="keyword token">var</span> intersection <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Set</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
+ <span class="keyword token">for</span> <span class="punctuation token">(</span><span class="keyword token">var</span> elem <span class="keyword token">of</span> setB<span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ <span class="keyword token">if</span> <span class="punctuation token">(</span><span class="keyword token">this</span><span class="punctuation token">.</span><span class="function token">has</span><span class="punctuation token">(</span>elem<span class="punctuation token">)</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ intersection<span class="punctuation token">.</span><span class="function token">add</span><span class="punctuation token">(</span>elem<span class="punctuation token">)</span><span class="punctuation token">;</span>
+ <span class="punctuation token">}</span>
+ <span class="punctuation token">}</span>
+ <span class="keyword token">return</span> intersection<span class="punctuation token">;</span>
+<span class="punctuation token">}</span>
+
+Set<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>difference <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>setB<span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ <span class="keyword token">var</span> difference <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Set</span><span class="punctuation token">(</span><span class="keyword token">this</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
+ <span class="keyword token">for</span> <span class="punctuation token">(</span><span class="keyword token">var</span> elem <span class="keyword token">of</span> setB<span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ difference<span class="punctuation token">.</span><span class="keyword token">delete</span><span class="punctuation token">(</span>elem<span class="punctuation token">)</span><span class="punctuation token">;</span>
+ <span class="punctuation token">}</span>
+ <span class="keyword token">return</span> difference<span class="punctuation token">;</span>
+<span class="punctuation token">}</span>
+
+<span class="comment token">//Examples</span>
+<span class="keyword token">var</span> setA <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Set</span><span class="punctuation token">(</span><span class="punctuation token">[</span><span class="number token">1</span><span class="punctuation token">,</span><span class="number token">2</span><span class="punctuation token">,</span><span class="number token">3</span><span class="punctuation token">,</span><span class="number token">4</span><span class="punctuation token">]</span><span class="punctuation token">)</span><span class="punctuation token">,</span>
+ setB <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Set</span><span class="punctuation token">(</span><span class="punctuation token">[</span><span class="number token">2</span><span class="punctuation token">,</span><span class="number token">3</span><span class="punctuation token">]</span><span class="punctuation token">)</span><span class="punctuation token">,</span>
+ setC <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Set</span><span class="punctuation token">(</span><span class="punctuation token">[</span><span class="number token">3</span><span class="punctuation token">,</span><span class="number token">4</span><span class="punctuation token">,</span><span class="number token">5</span><span class="punctuation token">,</span><span class="number token">6</span><span class="punctuation token">]</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
+
+setA<span class="punctuation token">.</span><span class="function token">isSuperset</span><span class="punctuation token">(</span>setB<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// =&gt; true</span>
+setA<span class="punctuation token">.</span><span class="function token">union</span><span class="punctuation token">(</span>setC<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// =&gt; Set [1, 2, 3, 4, 5, 6]</span>
+setA<span class="punctuation token">.</span><span class="function token">intersection</span><span class="punctuation token">(</span>setC<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// =&gt; Set [3, 4]</span>
+setA<span class="punctuation token">.</span><span class="function token">difference</span><span class="punctuation token">(</span>setC<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// =&gt; Set [1, 2]</span></code></pre>
+
+<h3 id="Relación_con_los_objetos_Array">Relación con los objetos <code>Array</code></h3>
+
+<pre class="brush: js">const myArray = ['value1', 'value2', 'value3'];
+
+// Utiliza el constructor para para crear un set con el mismo contenido que un array
+const mySet = new Set(myArray);
+
+mySet.has('value1'); // devuelve true
+
+// Utiliza la propagación para crear un array con los contenidos de un set
+console.log([...mySet]); // Muestra lo mismo utilizando myArray</pre>
+
+<h2 id="Especificaciones">Especificaciones</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">Especificación</th>
+ <th scope="col">Estado</th>
+ <th scope="col">Comentario</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('ES2015', '#sec-set-objects', 'Set')}}</td>
+ <td>{{Spec2('ES2015')}}</td>
+ <td>Definición inicial</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('ESDraft', '#sec-set-objects', 'Set')}}</td>
+ <td>{{Spec2('ESDraft')}}</td>
+ <td></td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2>
+
+<div class="hidden">La tabla de compatibilidad en esta página es generada desde información estructurada. Si desea contribuir, por favor revise la información en <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> y envie un pull request/merge request.</div>
+
+<p>{{Compat("javascript.builtins.Set")}}</p>
+
+<h2 id="Ver_también">Ver también</h2>
+
+<ul>
+ <li>{{jsxref("Map")}}</li>
+ <li>{{jsxref("WeakMap")}}</li>
+ <li>{{jsxref("WeakSet")}}</li>
+</ul>