首頁 > web前端 > js教程 > 主體

ES6的Set資料結構是什麼

一个新手
發布: 2017-09-09 13:57:55
原創
1683 人瀏覽過

ES6:Set

了解Set

ES6提供了資料結構Set。類似於數組,但是沒有重複值。

  • Set本身就是一個建構函數,用來產生Set資料結構

#
const s = new Set();
[2, 3, 5, 4, 5, 2, 2].forEach(x => s.add(x));for(let i of s ) {    console.log(i); //2 3 4 5 }
登入後複製
  • Set可以接受一個陣列(或類別數組物件)作為參數,用來初始化

var set = new Set([1, 2, 3, 4, 4]);
[...set]; // [1, 2, 3, 4]
登入後複製

可用於陣列去重[...new Set(array)]

Array.from()方法可以將Set結構轉換為陣列Array.from(new Set(array))

  • 在Set中加入值時,不會發生型別轉換(類似精確相等===),但要注意在Set裡NaN是等於自身的。另外兩個物件總是不相等的。

let set = new Set();let a = NaN;let b = NaN;
set.add(a);
set.add(b);
set; //{NaN} 只能加入一个,说明Set内部两个NaN是相等的
登入後複製

Set實例的屬性與方法

  • #屬性:

    • Set.prototype.constructor:建構函數,預設為Set函數

    • #Set.prototype.size:傳回實例的成員總數

  • #操作方法(方法的具體實作見:我對JS集合的簡單學習):

    • add(value ):新增一個值,回傳Set結構本身

    • delete(value):刪除某個值,回傳布林值

    • has(value):傳回布林值,表示是否為成員

    • clear():清除所有成員,無回傳值

s.add(1).add(2).add(2); //链式写法s.size(); //2s.has(3); //falses.delete(2);
s.has(2); //false
登入後複製
  • 遍历方法

    • keys():返回键名的遍历器(什么是遍历器?Iterator)

    • values():返回键值的遍历器

    • entries():返回键值对的遍历器

    • forEach():使用回调函数遍历每个成员

这里要注意Set的键名和键值是同一个值,所以key()和values()行为是一致的。

let set = new Set(['red', 'green', 'no']);for(let item of set.keys()) {    console.log(item); //red green no}for(let item of set.values()) {    console.log(item); //red green no}for(let item of set.entries()) {    console.log(item); //['red': 'red'] ['green': 'green'] ['no': 'no']}//对每个成员执行某种操作,参数依次为键值、键名、集合本身new Set([1, 2, 3]).forEach((value, key) => console.log(value * 2)); //2 4 6
登入後複製

操作集合

let a = new Set([1, 2, 3]);let b = new Set([4, 3, 2]);//并集let union = new Set([...a, ...b]); //{1, 2, 3, 4}//交集let intersect = new Set([...a].filter(x => b.has(x))); //{2, 3}//差集let difference = new Set([...a].filter(x => !b.has(x))); //{1}
登入後複製

号外:扩展运算符(...)内部使用for...of循环,所以应该知道for of是干嘛的吧

数组的map()filter()可用于Set

let set = new Set([1, 2, 3]);set = new Set([...set].map(x => x * 2)); //set: {2, 4, 6}let set = new Set([1, 2, 3, 4, 5]);set = new Set([...set].filter(x => (x % 2) == 0)); //set {2, 4}
登入後複製

以上是ES6的Set資料結構是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!