似于數(shù)組,但它的一大特性就是所有元素都是唯一的,沒有重復(fù)轰胁。
我們可以利用這一唯一特性進(jìn)行數(shù)組的去重工作。
1.set是一種數(shù)據(jù)結(jié)構(gòu)朝扼,可以認(rèn)為是數(shù)組赃阀;
2.set里面添加的對(duì)象即使相同也是不相等的,例如:set.add({}); set.add({}); 可以同時(shí)存在擎颖;
3.Set.prototype.constructor榛斯,構(gòu)造函數(shù),默認(rèn)是set函數(shù)搂捧;
4.Array.from方法可以將set結(jié)構(gòu)轉(zhuǎn)化為數(shù)組驮俗;
Array.from(new Set([...a,...b]))
es6 set方法可分為兩大類:
1、操作方法(用于數(shù)據(jù)操作)“add(value)”异旧、“delete(value)”意述、“has(value)”、clear()吮蛹;
add(value) 添加數(shù)據(jù)荤崇,并返回新的 Set 結(jié)構(gòu)
delete(value) 刪除數(shù)據(jù),返回一個(gè)布爾值潮针,表示是否刪除成功
has(value) 查看是否存在某個(gè)數(shù)據(jù)术荤,返回一個(gè)布爾值
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 此處返回值是個(gè)boolean 表示 是否刪除成功
// 查看是否存在數(shù)據(jù) 4
let hasSet = set.has(4);
console.log(hasSet); // false
// 清除所有數(shù)據(jù)
set.clear();
console.log(set); // Set(0) {}
2每篷、遍歷方法(用于遍歷數(shù)據(jù))keys()瓣戚、values()、entries()焦读、forEach()子库。
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
Set的屬性
常用的屬性就一個(gè):size--返回 Set 實(shí)例的成員總數(shù)。
let s = new Set([1, 2, 3]);
console.log( s.size ); // 3