ES6中的Set方法總結


操作方法:

  add(value):添加某個值,返回 Set 結構本身。
  delete(value):刪除某個值,返回一個布爾值,表示刪除是否成功。
  has(value):返回一個布爾值,表示該值是否為Set的成員。
  clear():清除所有成員,沒有返回值。

 

遍歷方法

  keys():返回鍵名的遍歷器
  values():返回鍵值的遍歷器
  entries():返回鍵值對的遍歷器
  forEach():使用回調函數遍歷每個成員

 

  • 與數組搭配,去掉重復的元素
let set = new Set(['1', '2', '2','3']);
let array = [...set];
console.log(array);//(3) ["1", "2", "3"]

 

  • 實現並集、交集、差集
let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);

// 並集
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}

// 交集
let intersect = new Set([...a].filter(x => b.has(x)));
// set {2, 3}

// 差集
let difference = new Set([...a].filter(x => !b.has(x)));
// Set {1}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM