es6 set方法可分為兩大類:1、操作方法“add(value)”、“delete(value)”、“has(value)”、clear();2、遍歷方法keys()、values()、entries()、forEach()。
本教程操作環(huán)境:windows7系統(tǒng)、ECMAScript 6版、Dell G3電腦。
ES6 提供了新的數(shù)據(jù)結(jié)構(gòu) Set。它類似于數(shù)組,但是成員的值都是唯一的,沒有重復(fù)的值。
很多時候我們把Set叫做 集合,但是,Set可以是集合,集合不一定是Set。
特性:唯一性=>不重復(fù)=>能夠?qū)?shù)據(jù)進(jìn)行去重操作。
創(chuàng)建Set
Set 本身是一個構(gòu)造函數(shù),調(diào)用構(gòu)造函數(shù)用來生成 Set 數(shù)據(jù)結(jié)構(gòu)。
關(guān)鍵詞 標(biāo)識符 = new Set();
例
let i = new Set();
Set 函數(shù)可以接受一個數(shù)組(或類似數(shù)組的對象)作為參數(shù),用來進(jìn)行數(shù)據(jù)初始化。
let i = new Set([1, 2, 3, 4, 4]); //會得到 set{1, 2, 3, 4,}
注:如果初始化時給的值有重復(fù)的,會自動去除。集合并沒有字面量聲明方式,只能用new關(guān)鍵字來聲明。
Set的屬性
常用的屬性就一個:size–返回 Set 實(shí)例的成員總數(shù)。
let s = new Set([1, 2, 3]); console.log( s.size ); // 3
Set的方法
Set 實(shí)例的方法分為兩大類:操作方法(用于數(shù)據(jù)操作)和遍歷方法(用于遍歷數(shù)據(jù))。
操作方法:
-
add(value) 添加數(shù)據(jù),并返回新的 Set 結(jié)構(gòu)
-
delete(value) 刪除數(shù)據(jù),返回一個布爾值,表示是否刪除成功
-
has(value) 查看是否存在某個數(shù)據(jù),返回一個布爾值
-
clear() 清除所有數(shù)據(jù),沒有返回值
let set = new Set([1, 2, 3, 4, 4]); // 添加數(shù)據(jù) 5 let addSet = set.add(5); console.log(addSet); // Set(5) {1, 2, 3, 4, 5} // 刪除數(shù)據(jù) 4s let delSet = set.delete(4); console.log(delSet); // true 此處返回值是個boolean 表示 是否刪除成功 // 查看是否存在數(shù)據(jù) 4 let hasSet = set.has(4); console.log(hasSet); // false // 清除所有數(shù)據(jù) set.clear(); console.log(set); // Set(0) {}
遍歷方法:
Set 提供了三個遍歷器生成函數(shù)和一個遍歷方法。
-
keys() 返回一個鍵名的遍歷器
-
values() 返回一個鍵值的遍歷器
-
entries() 返回一個鍵值對的遍歷器
-
forEach() 使用回調(diào)函數(shù)遍歷每個成員
let color = new Set(["red", "green", "blue"]); for(let item of color.keys()){ console.log(item); } // red // green // blue for(let item of color.values()){ console.log(item); } // red // green // blue for(let item of color.entries()){ console.log(item); } // ["red", "red"] // ["green", "green"] // ["blue", "blue"] color.forEach((item) => { console.log(item) }) // red // green // blue
【推薦學(xué)習(xí):javascript高級教程】