1. 程式人生 > >ES6 -Set 和 Map 數據結構

ES6 -Set 和 Map 數據結構

gin UNC uncaught pre console fine reac error: div

一、set

1.set數據結構:類似數組,但是裏面不能有重復值

2.set語法, new Set([])

let set=new Set([1,2,1]);
console.log(set);// {1, 2}

3.set 方法

// add() 增加,返回增加後的set
console.log(set.add(3)); // {1, 2,3}

// delete() 刪除,返回true或false
console.log(set.delete(2));// true

// has() 判斷是否存在某一項,返回true或false
console.log(set.has(1));//true

// clear() 清空
set.clear(); console.log(set);//{}

4.set 屬性

// size  查看長度
console.log(set.size);//2

5.set循環

// for of : key,value相等

let set=new Set([1,2,3]);

for(let item of set){//默認是values
    console.log(item);// 1 2 3
}

for(let item of set.keys()){
    console.log(item);// 1 2 3
}

for(let item of set.values()){
    console.log(item);
// 1 2 3 } for(let item of set.entries()){ console.log(item);// [1, 1] [2, 2] [3, 3] } set.forEach((value,index)=>{ console.log(value,index);//1 1,2 2,3 3 })

6.set 用法

// 1.數組去重

let arr=[1,2,3,3,1,2,3,1,2];

let set=new Set(arr);
let newArr=[...set]; // set 數據結構變成數組

console.log(newArr);//[1, 2, 3]
// 2.set 利用數組的方法 let set=new Set([1,2,3]); let arr=[...set]; arr=arr.map((val)=>{ return val*2; }); set=new Set(arr);//{2, 4, 6}

7. set 註意

// set裏面只能是數組
let set=new Set({a:1});
console.log(set);// error:#<Object> is not iterable

// 可以通過add()方法增加
let set=new Set();
let json={
    a:1,
    b:2
};
let json1={
    a:1,
    b:3
};
set.add(json);
set.add(json1);

console.log(set);

set.forEach((item)=>{
    console.log(item);//{a: 1, b: 2} ,{a: 1, b: 3}
})

二、WeakSet() 存儲json,但是初始不可以增加,只能用add增加 ,沒有size屬性,clear()方法

// 但是初始不可以增加=new WeakSet({})
let set=new WeakSet({
    a:1,
    b:2
}); //Uncaught TypeError: #<Object> is not iterable


// 只能用add增加 ,沒有size屬性
let set=new WeakSet();
set.add({a:1})
console.log(set);
console.log(set.size); //undefined

三、Map

Map:類似json,但是json的key 只能是字符串

map的key 可以是任意leix

1.Map語法

// 不可以直接增加{}
let map=new Map({a:1}); //error:#<Object> is not iterable
console.log(map);

// 通過set設置值
let map=new Map();
map.set(‘a‘,‘asd‘);
console.log(map);//{"a" => "asd"}

2.map 方法

let map=new Map();
let json={a:1};
// set(key,value) 設置值 ,返回設置後的set值
console.log(map.set(‘a‘,‘asd‘));//{"a" => "asd"}
console.log(map.set(json,‘aaa‘));//{"a" => "asd", {…} => "aaa"}

// get(key)獲取值
console.log(map.get(json));//aaa

// delete(key) 刪除一項,返回true或false
console.log(map.delete(json));//true

// has(key) 判斷有沒有,返回true或false
console.log(map.has(json));//false

// clear() 清空,無返回值
console.log(map.clear());//undefined

console.log(map);//{}

3.map 循環

for(let [key,value] of map){}//默認 entries()
for(let key of map.keys()){}
for(let value of map.values()){}
for(let [key,value] of map.entries){}
map.forEach((value,index)=>{});

四、WeakMap():key只能是對象

let map=new WeakMap();

let json={a:1};

map.set(json,1);
map.set(‘a‘,1);//Uncaught TypeError: Invalid value used as weak map key

console.log(map);

五、總結:

Set裏面是數組,不重復,

Map 對json的增強,key可以是任意類型

ES6 -Set 和 Map 數據結構