aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/javascript/reference/global_objects/set/index.html
blob: 2b3f80fdd152f71f363c713e514facdabea67d76 (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
231
232
233
234
235
236
237
238
239
240
241
242
243
---
title: Set
slug: Web/JavaScript/Reference/Global_Objects/Set
tags:
  - ECMAScript 2015
  - Global Objects
  - JavaScript
  - Object
  - set
translation_of: Web/JavaScript/Reference/Global_Objects/Set
---
<div>{{JSRef}}</div>

<p><strong><code>Set</code></strong> 物件可讓你儲存任何類型的唯一值(unique),不論是{{Glossary("Primitive", "基本型別(primitive)值")}}或物件參考(references)。</p>

<div>{{EmbedInteractiveExample("pages/js/set-prototype-constructor.html")}}</div>



<h2 id="語法">語法</h2>

<pre class="syntaxbox notranslate">new Set([<em>iterable</em>]);</pre>

<h3 id="參數">參數</h3>

<dl>
 <dt><code>iterable</code></dt>
 <dd>若一個<a href="/zh-TW/docs/Web/JavaScript/Reference/Statements/for...of">可迭代物件</a>被傳入,其所有的元素將會被加入至新的 <code>Set</code>。若你沒有指定此參數,或參數值為 <code>null</code>,則新的 <code>Set</code> 會是空的。</dd>
</dl>

<h3 id="回傳值">回傳值</h3>

<p>一個新的 <code>Set</code> 物件。</p>

<h2 id="描述">描述</h2>

<p><code>Set</code> 對象是數值的收集器。您可以按插入順序迭代收集器中的元素。在 <code>Set</code> 裡的元素只會出現一次<strong></strong> 意即在<code>Set</code>裡的元素都是獨一無二</p>

<h3 id="值的相等性">值的相等性</h3>

<p>因為在 Set 裡每個值都是獨立的,所以都會檢查值的相等性。在早期的ECMAScript規範版本中,此處算法跟基於===操作符中使用的算法並不相同。具體來說,在 <code>Set</code>裡+0(在嚴格模式是和-0相等)和-0是不同的值。然而在 ECMAScript 2015規範中這點已被更改。請參閱 <a href="#Browser_compatibility">瀏覽器兼容性</a> 中的"Value equality for -0 and 0"。</p>

<p>另外,NaN和undefined都可以被放置在Set 中, NaN之間被視為相同的值(儘管 NaN !== NaN)。</p>

<dl>
 <dt><code>Set.length</code></dt>
 <dd>The value of the <code>length</code> property is 0.</dd>
 <dt>{{jsxref("Set.@@species", "get Set[@@species]")}}</dt>
 <dd>The constructor function that is used to create derived objects.</dd>
 <dt>{{jsxref("Set.prototype")}}</dt>
 <dd>Represents the prototype for the <code>Set</code> constructor. Allows the addition of properties to all <code>Set</code> objects.</dd>
</dl>

<h2 id="Set_物件實體"><code>Set</code> 物件實體</h2>

<p>All <code>Set</code> instances inherit from {{jsxref("Set.prototype")}}.</p>

<h3 id="屬性">屬性</h3>

<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Set/prototype','Properties')}}</p>

<h3 id="方法">方法</h3>

<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Set/prototype','Methods')}}</p>

<h2 id="範例">範例</h2>

<h3 id="使用_Set_物件">使用 <code>Set</code> 物件</h3>

<pre class="brush: js notranslate">var mySet = new Set();

mySet.add(1); // Set [ 1 ]
mySet.add(5); // Set [ 1, 5 ]
mySet.add(5); // Set [ 1, 5 ]
mySet.add('some text'); // Set [ 1, 5, 'some text' ]
var o = {a: 1, b: 2};
mySet.add(o);

mySet.add({a: 1, b: 2}); // o is referencing a different object so this is okay

mySet.has(1); // true
mySet.has(3); // false, 3 has not been added to the 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); // removes 5 from the set
mySet.has(5);    // false, 5 has been removed

mySet.size; // 4, we just removed one value
console.log(mySet);// Set [ 1, "some text", Object {a: 1, b: 2}, Object {a: 1, b: 2} ]</pre>

<h3 id="迭代_Sets">迭代 Sets</h3>

<pre class="brush: js notranslate">// iterate over items in set
// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}
for (let item of mySet) console.log(item);

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

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

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

// convert Set object to an Array object, with <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from">Array.from</a>
var myArr = Array.from(mySet); // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}]

// 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([...set1].filter(x =&gt; set2.has(x)));

// difference can be simulated via
var difference = new Set([...set1].filter(x =&gt; !set2.has(x)));

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

// 1
// 2
// 3
// 4</pre>

<h3 id="實作基本的_set_操作">實作基本的 set 操作</h3>

<pre class="brush: js notranslate">Set.prototype.isSuperset = function(subset) {
    for (var elem of subset) {
        if (!this.has(elem)) {
            return false;
        }
    }
    return true;
}

Set.prototype.union = function(setB) {
    var union = new Set(this);
    for (var elem of setB) {
        union.add(elem);
    }
    return union;
}

Set.prototype.intersection = function(setB) {
    var intersection = new Set();
    for (var elem of setB) {
        if (this.has(elem)) {
            intersection.add(elem);
        }
    }
    return intersection;
}

Set.prototype.difference = function(setB) {
    var difference = new Set(this);
    for (var elem of setB) {
        difference.delete(elem);
    }
    return difference;
}

//Examples
var setA = new Set([1, 2, 3, 4]),
    setB = new Set([2, 3]),
    setC = new Set([3, 4, 5, 6]);

setA.isSuperset(setB); // =&gt; true
setA.union(setC); // =&gt; Set [1, 2, 3, 4, 5, 6]
setA.intersection(setC); // =&gt; Set [3, 4]
setA.difference(setC); // =&gt; Set [1, 2]

</pre>

<h3 id="與_Array_物件關聯">與 <code>Array</code> 物件關聯</h3>

<pre class="brush: js notranslate">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([...mySet]); // Will show you exactly the same Array as myArray</pre>

<h3 id="與_Strings_關聯">與 <code>Strings</code> 關聯</h3>

<pre class="brush: js notranslate">var text = 'India';

var mySet = new Set(text);  // Set ['I', 'n', 'd', 'i', 'a']
mySet.size;  // 5
</pre>

<h2 id="規範">規範</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES2015', '#sec-set-objects', 'Set')}}</td>
   <td>{{Spec2('ES2015')}}</td>
   <td>Initial definition.</td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-set-objects', 'Set')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="瀏覽器相容性">瀏覽器相容性</h2>



<p>{{Compat("javascript.builtins.Set")}}</p>

<h2 id="參見">參見</h2>

<ul>
 <li>{{jsxref("Map")}}</li>
 <li>{{jsxref("WeakMap")}}</li>
 <li>{{jsxref("WeakSet")}}</li>
</ul>