aboutsummaryrefslogtreecommitdiff
path: root/files/es/web/javascript/reference/global_objects/set/index.html
blob: db091b3a597a953635ccb11141118b6a43a9d01c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
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><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>