Obiekt Set
umożliwia przechowywanie unikalnych wartości każdego typu, zarówno primitywów jak i obiektów.
Składnia
new Set([iterable]);
Parametry
iterable
- Jeżeli przekażesz obiekt iterowalny, wszystkie jego elementy zostaną dodane do nowego
Set
. Podczas gdy nie przekażemy żadnego parametru lub wartość parametru będzie równanull
, zostanie stworzony pustySet
.
Zwracana wartość
Nowy obiekt Set
.
Opis
Obiekt Set
jest kolekcją wartości. Możesz iterować po elementach Set
w kolejności, w której zostały dodane. Wartość w Set
może występować tylko jeden raz.
Równość wartości
Dlatego, że każda wartość w Set
musi być unikalna, musi zostać to sprawdzone. We wcześniejszych specyfikacjach ECMAScript nie było to oparte na tym samym algorytmie co w przypadku operatora ===. Konkretnie dla Set +0 (co jest tym samym co -0) i -0 były innymi wartościami. W specyfikacji ECMAScript 2015 zostało to zmienione. Zobacz "Value equality for -0 and 0" w tabeli Kompatybilność z przeglądarkami.
NaN
i undefined
mogą być przechowywane w Set
. NaN
w Set
uważane jest za równe NaN
, podczas gdy NaN !== NaN
zwraca true
Własności
Set.length
- Wartość
length
zawsze wynosi 0. get Set[@@species]
- Funkcja wykorzystywana do stworzenia pochodnych obiektów.
Set.prototype
- Reprezentuje prototyp konstruktora
Set.
Pozwala na dodanie własności do obiektuSet
.
Instancje Set
Wszystkie instancje Set
dziedziczą od Set.prototype
.
Własności
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.
Metody
Set.prototype.add(value)
- Appends a new element with the given value to the
Set
object. Returns theSet
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 thatSet.prototype.has(value)
would have previously returned.Set.prototype.has(value)
will returnfalse
afterwards. Set.prototype.entries()
- Returns a new
Iterator
object that contains an array of[value, value]
for each element in theSet
object, in insertion order. This is kept similar to theMap
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 theSet
object, in insertion order. If athisArg
parameter is provided toforEach
, it will be used as thethis
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 newIterator
object that contains the values for each element in theSet
object in insertion order. Set.prototype.values()
- Returns a new
Iterator
object that contains the values for each element in theSet
object in insertion order. Set.prototype[@@iterator]()
- Returns a new
Iterator
object that contains the values for each element in theSet
object in insertion order.
Przykłady
Użycie obiektu Set
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 jest referencją do innego obiektu, więc dwa obiekty zostają dodane do Set. mySet.has(1); // true mySet.has(3); // false, 3 nie zostało dodane do 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); // Usuwa 5 z Set. mySet.has(5); // false, 5 zostało usunięte. mySet.size; // 4, usuneliśmy jedną wartość. console.log(mySet);// Set {1, "some text", Object {a: 1, b: 2}, Object {a: 1, b: 2}}
Iterowanie po Set.
// Iterowanie po items w Set. // wypisuje items w kolejności: 1, "some text", {"a": 1, "b": 2} for (let item of mySet) console.log(item); // wypisuje items w kolejności: 1, "some text", {"a": 1, "b": 2} for (let item of mySet.keys()) console.log(item); // wypisuje items w kolejności: 1, "some text", {"a": 1, "b": 2} for (let item of mySet.values()) console.log(item); // wypisuje items w kolejności: 1, "some text", {"a": 1, "b": 2} //(key i value są takie same) for (let [key, value] of mySet.entries()) console.log(key); // zamienia Set na Array, przy użyciu Array.from var myArr = Array.from(mySet); // [1, "some text", {"a": 1, "b": 2}] // następujące funkcje również zadziałają, jeżeli skrypt odpalony jest w dokumencie HTML mySet.add(document.body); mySet.has(document.querySelector('body')); // true // zamiana Array na Set i na odwrót mySet2 = new Set([1, 2, 3, 4]); mySet2.size; // 4 [...mySet2]; // [1, 2, 3, 4] // Set z wartościami, które są w set1 i set2, może być uzyskany następująco var intersection = new Set([...set1].filter(x => set2.has(x))); // Set z różnicami wartości set1 i set2 może być uzyskany następująco var difference = new Set([...set1].filter(x => !set2.has(x))); // iterowanie po Set za pomocą .forEach mySet.forEach(function(value) { console.log(value); }); // 1 // 2 // 3 // 4
Implementacja podstawowych operacji Set
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; } // Przykłady var setA = new Set([1, 2, 3, 4]), setB = new Set([2, 3]), setC = new Set([3, 4, 5, 6]); setA.isSuperset(setB); // => true setA.union(setC); // => Set [1, 2, 3, 4, 5, 6] setA.intersection(setC); // => Set [3, 4] setA.difference(setC); // => Set [1, 2]
Relacje z Tablicami (Array
)
var myArray = ['value1', 'value2', 'value3']; // Użycie konstruktora Set do zamiany Array na Set. var mySet = new Set(myArray); mySet.has('value1'); // => true // Użycie spread operator do zamiany Set na Array. console.log([...mySet]); // Will show you exactly the same Array as myArray
Specyfikacje
Specyfikacja | Status | Komentarz |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Set' in that specification. |
Standard | Początkowa definicja. |
ECMAScript Latest Draft (ECMA-262) The definition of 'Set' in that specification. |
Draft |
Kompatybilność przeglądarek
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support |
38 [1] |
12 | 13 (13) | 11 | 25 | 7.1 |
Constructor argument: new Set(iterable) |
38 | 12 | 13 (13) | No support | 25 | 9.0 |
iterable | 38 | 12 | 17 (17) | No support | 25 | 7.1 |
Set.add() returns the set |
38 | 12 | 13 (13) | No support | 25 | 7.1 |
Set.clear() |
38 | 12 | 19 (19) | 11 | 25 | 7.1 |
Set.keys(), Set.values(), Set.entries() |
38 | 12 | 24 (24) | No support | 25 | 7.1 |
Set.forEach() |
38 | 12 | 25 (25) | 11 | 25 | 7.1 |
Value equality for -0 and 0 | 38 | 12 | 29 (29) | No support | 25 | 9 |
Constructor argument: new Set(null) |
(Yes) | 12 | 37 (37) | 11 | (Yes) | 7.1 |
Monkey-patched add() in Constructor |
(Yes) | 12 | 37 (37) | No support | (Yes) | 9 |
Set[@@species] |
51 | 13 | 41 (41) | No support | 38 | 10 |
Set() without new throws |
(Yes) | 12 | 42 (42) | 11 | (Yes) | 9 |
Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|---|
Basic support | No support | 38 [1] | (Yes) | 13.0 (13) | No support | No support | 8 |
Constructor argument: new Set(iterable) |
No support | 38 | (Yes) | 13.0 (13) | No support | No support | 9 |
iterable | No support | No support | (Yes) | 17.0 (17) | No support | No support | 8 |
Set.clear() |
No support | 38 | (Yes) | 19.0 (19) | No support | No support | 8 |
Set.keys(), Set.values(), Set.entries() |
No support | 38 | (Yes) | 24.0 (24) | No support | No support | 8 |
Set.forEach() |
No support | 38 | (Yes) | 25.0 (25) | No support | No support | 8 |
Value equality for -0 and 0 | No support | 38 | (Yes) | 29.0 (29) | No support | No support | 9 |
Constructor argument: new Set(null) |
? | (Yes) | (Yes) | 37.0 (37) | ? | ? | 8 |
Monkey-patched add() in Constructor |
? | (Yes) | (Yes) | 37.0 (37) | ? | ? | 9 |
Set[@@species] |
? | ? | (Yes) | 41.0 (41) | ? | ? | 10 |
Set() without new throws |
? | ? | (Yes) | 42.0 (42) | ? | ? | 9 |
[1] The feature was available behind a preference from Chrome 31. In chrome://flags
, activate the entry “Enable Experimental JavaScript”.