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