介紹
ECMAScript 6(以下簡(jiǎn)稱ES6)是JavaScript語(yǔ)言的下一代標(biāo)準(zhǔn)。因?yàn)楫?dāng)前版本的ES6是在2015年發(fā)布的,所以又稱ECMAScript 2015。
Sets 是ES6(ES2015)中一個(gè)新的對(duì)象類型,用來(lái)創(chuàng)建一系列唯一值的集合。集合中的值可以是簡(jiǎn)單的原始類型如字符串(strings)或整數(shù)(integers),也可以是更復(fù)雜的對(duì)象類型如對(duì)象字面量或者數(shù)組。
基本方法
下面是基本的set及其方法(add, size, has, forEach, delete, clear)的簡(jiǎn)單示例:
let animals = new Set();animals.add('🐷');animals.add('🐼');animals.add('🐢');animals.add('🐿');console.log(animals.size); // 4animals.add('🐼');console.log(animals.size); // 4console.log(animals.has('🐷')); // trueanimals.delete('🐷');console.log(animals.has('🐷')); // falseanimals.forEach(animal => { console.log(`Hey ${animal}!`);});// Hey 🐼!// Hey 🐢!// Hey 🐿!animals.clear();console.log(animals.size); // 0初始化
下面是另一個(gè)將數(shù)組作為初始值傳進(jìn)set的示例。需要主要的是初始化的數(shù)組是如何被解構(gòu)的,但是隨后添加的數(shù)組將以數(shù)組的形式存在:
let myAnimals = new Set(['🐷', '🐢', '🐷', '🐷']);myAnimals.add(['🐨', '🐑']);myAnimals.add({ name: 'Rud', type: '🐢' });console.log(myAnimals.size); // 4myAnimals.forEach(animal => { console.log(animal);});// 🐷// 🐢// ["🐨", "🐑"]// Object { name: "Rud", type: "🐢" }字符串也是一個(gè)有效的迭代,所以也可以被傳入來(lái)初始化一個(gè)set:
console.log('Only unique characters will be in this set.'.length); // 43let sentence = new Set('Only unique characters will be in this set.');console.log(sentence.size); // 18For...of遍歷
除了在一個(gè)set上可以使用forEach外,for...of循環(huán)也可以被用來(lái)遍歷sets:
let moreAnimals = new Set(['🐺', '🐴', '🐕', '🐇']);for (let animal of moreAnimals) { console.log(`Howdy ${ animal }`);}// Howdy 🐺// Howdy 🐴// Howdy 🐕// Howdy 🐇Keys 和 Values
Sets也有keys和values方法,由于keys是values的別名,所以兩個(gè)方法其實(shí)是完成一樣的事情。使用兩者中的任何一個(gè)方法都會(huì)返回一個(gè)新的可迭代的對(duì)象,該對(duì)象的值與添加到集合中的順序相同。
let partyItems = new Set(['🍕', '🍾', '🎊']);let items = partyItems.values();console.log(items.next());console.log(items.next());console.log(items.next());console.log(items.next().done);// Object {// done: false,// value: "🍕"http:// }// Object {// done: false,// value: "🍾"http:// }// Object {// done: false,// value: "🎊"http:// }// true總結(jié)
以上就是這篇文章的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)武林網(wǎng)的支持。
注:
原文: Introduction to Sets in JavaScript
作者: alligatorio
譯者:smallbone
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注