Переклад цієї статті ще не завершено. Будь ласка, допоможіть перекласти цю статтю з англійської мови
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Синтаксис
new Set([iterable]);
Параметри
iterable- Якщо передається об'єкт, що ітерується, то всі його елементи будуть додані до нового
Set. Якщо цей параметр не визначений або має значення null, тоді новийSetбуде порожнім.
Значення, що повертається
Новий об'єкт Set.
Опис
Об'єкти Set - це колекції унікальних значень. Ви можете перебирати елементи Set у порядку вставки. Одне значення в Set може зустрічатися лише один раз; воно є унікальним в колекції Set.
Еквівалентність значення
Через те, що кожне значення в Set має бути унікальним, еквівалентність значення буде перевірена. У попередній версії специфікації ECMAScript це не було базовано на такому самому алгоритмі, що використовує оператор ===. Конкретніше, для Set +0 (що є суворо рівним -0 ) та -0 є різними значеннями. Проте, це було змінено у специфікації ECMAScript 2015. Дивіться більш детально про "Еквівалентність значень -0 і 0" у таблиці браузерної сумісності.
До того ж, NaN та undefined також можуть зберігатися в Set. NaN вважається тим самим, що і NaN (хоча, NaN !== NaN ).
Властивості
Set.length- Значення властивості
lengthє 0. get Set[@@species]- Функція-конструктор, що використовується для строрення derived об'єктів.
Set.prototype- Представляє прототип для конструктора
Set. Дозволяє додавання властивостей до всіхSetоб'єктів.
Set instances
Усі Set сутності наслідуються від Set.prototype.
Властивості
Методи
Приклади
Використання об'єкта 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 має посилання на інший об'єкт, тому це ок
mySet.has(1); // true
mySet.has(3); // false, 3 не було додано в 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); // видаляє 5 з set
mySet.has(5); // false, 5 було видалено
mySet.size; // 4, ми щойно видалили одне значення
console.log(mySet);// Set {1, "some text", Object {a: 1, b: 2}, Object {a: 1, b: 2}}
Перебирання Set
// перебираємо елементи в set
// виводить елементи у послідовності: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}
for (let item of mySet) console.log(item);
// виводить елементи у послідовності: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}
for (let item of mySet.keys()) console.log(item);
// виводить елементи у послідовності: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}
for (let item of mySet.values()) console.log(item);
// виводить елементи у послідовності: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}
//(key та value тут мають одне й те саме значення)
for (let [key, value] of mySet.entries()) console.log(key);
// конвертує об'єкт Set в об'єкт Array за допомогою Array.from
var myArr = Array.from(mySet); // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}]
// наступне також буде працювати, якщо буде запущено в HTML документі
mySet.add(document.body);
mySet.has(document.querySelector('body')); // true
// конвертація між Set та Array
mySet2 = new Set([1, 2, 3, 4]);
mySet2.size; // 4
[...mySet2]; // [1, 2, 3, 4]
// Перетинання може симулюватися через
var intersection = new Set([...set1].filter(x => set2.has(x)));
// різниця може бути симульована через
var difference = new Set([...set1].filter(x => !set2.has(x)));
// Перебирання елементів Set за допомогою forEach
mySet.forEach(function(value) {
console.log(value);
});
// 1
// 2
// 3
// 4
Імплементація базових операцій 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;
}
//Приклади
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]
Зв'язок з об'єктами Array
var myArray = ['value1', 'value2', 'value3'];
// Використовуйте звичайний конструктор Set для трансформації Array у Set
var mySet = new Set(myArray);
mySet.has('value1'); // повертає true
// Використовуйте оператор spread для трансформації Set у Array.
console.log([...mySet]); // Виведе у точності такий самий Array як і myArray
Зв'язок зі Strings
var text = 'India';
var mySet = new Set(text); // Set {'I', 'n', 'd', 'i', 'a'}
mySet.size; // 5
Specifications
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Set' in that specification. |
Standard | Initial definition. |
| ECMAScript (ECMA-262) The definition of 'Set' in that specification. |
Living Standard |
Browser compatibility
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Set | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 13 | IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Firefox Android Full support 14 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support 3.0 | nodejs
Full support
0.12
|
Set() constructor | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 13 | IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Firefox Android Full support 14 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support 3.0 | nodejs
Full support
0.12
|
add | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 13 | IE
Partial support
11
| Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Firefox Android Full support 14 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support 3.0 | nodejs
Full support
0.12
|
clear | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 19 | IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Firefox Android Full support 19 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support 3.0 | nodejs Full support 0.12 |
delete | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 13 | IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Firefox Android Full support 14 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support 3.0 | nodejs
Full support
0.12
|
entries | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 24 | IE No support No | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Firefox Android Full support 24 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support 3.0 | nodejs Full support 0.12 |
forEach | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 25 | IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Firefox Android Full support 25 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support 3.0 | nodejs Full support 0.12 |
has | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 13 | IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Firefox Android Full support 14 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support 3.0 | nodejs
Full support
0.12
|
| Key equality for -0 and 0 | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 25 | Safari Full support 9 | WebView Android Full support 38 | Chrome Android Full support 38 | Firefox Android Full support 29 | Opera Android Full support 25 | Safari iOS Full support 9 | Samsung Internet Android Full support 3.0 | nodejs Full support 4.0.0 |
size | Chrome Full support 38 | Edge Full support 12 | Firefox
Full support
19
| IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Firefox Android
Full support
19
| Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support 3.0 | nodejs Full support 0.12 |
values | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 24 | IE No support No | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Firefox Android Full support 24 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support 3.0 | nodejs Full support 0.12 |
@@iterator | Chrome Full support 43 | Edge Full support 12 | Firefox
Full support
36
| IE No support No | Opera Full support 30 | Safari Full support 9 | WebView Android Full support 43 | Chrome Android Full support 43 | Firefox Android
Full support
36
| Opera Android Full support 30 | Safari iOS Full support 9 | Samsung Internet Android Full support 4.0 | nodejs Full support 0.12 |
@@species | Chrome Full support 51 | Edge Full support 13 | Firefox Full support 41 | IE No support No | Opera Full support 38 | Safari Full support 10 | WebView Android Full support 51 | Chrome Android Full support 51 | Firefox Android Full support 41 | Opera Android Full support 41 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs
Full support
6.5.0
|
Legend
- Full support
- Full support
- Partial support
- Partial support
- No support
- No support
- See implementation notes.
- See implementation notes.
- User must explicitly enable this feature.
- User must explicitly enable this feature.
- Uses a non-standard name.
- Uses a non-standard name.