map存儲的是一個個的鍵值對羊初。主要特性介紹如下:
1 獲取map
- 構(gòu)造函數(shù)+set方法
let mapList = new Map();
mapList.set('name','zhangsan');
console.log(mapList);//{"name" => "zhangsan"}
- 構(gòu)造函數(shù)初始化方法 傳入一個特殊的二維數(shù)組
let mapList = new Map(
[['name','zhangsan'],
['age',18]]
);
console.log(mapList );//{"name" => "zhangsan", "age" => 18}
需要注意的是內(nèi)層數(shù)組元素個數(shù)都為2,映射為一個鍵值對,超過2個會被忽略久妆,1個會認(rèn)為該鍵值對值為undefiend "name" => undefined
跨跨,0個會認(rèn)為該鍵值對鍵與值均為undefiend undefined => undefined
2 map的長度size
let mapList = new Map(
[['name','zhangsan'],
['age',18]]
);
console.log(mapList.size);//2
3 map的增刪改查操作
- 增 set方法設(shè)置不存在的鍵時即為增
let mapList = new Map(
[['name','zhangsan'],
['age',18]]
);
mapList.set('count',90);
console.log(mapList);
//{"name" => "zhangsan", "age" => 18, "count" => 90}
- 刪 mapList.delete(key),mapList.clear()
let mapList = new Map(
[['name','zhangsan'],
['age',18]]
);
mapList.delete('count');
console.log(mapList);
//{"name" => "zhangsan", "age" => 18}
mapList.clear();
console.log(mapList);
//{}
- 改 mapList.set(key)設(shè)置已有鍵key時即為更改
let mapList = new Map(
[['name','zhangsan'],
['age',18]]
);
mapList.set('name','lisi');
console.log(mapList);
//{"name" => "lisi", "age" => 18}
- 查 mapList.get(key)即獲取對應(yīng)鍵的值,mapList.has(key)即判斷有無該鍵key
let mapList = new Map(
[['name','zhangsan'],
['age',18]]
);
console.log(mapList.has('name'));//true
console.log(mapList.get('name'));//zhangsan
4 遍歷
- let .. of
let mapList = new Map(
[['name','zhangsan'],
['age',18]]
);
for(let key of mapList.keys()){
console.log(key);
}
//name age
for(let value of mapList.values()){
console.log(value);
}
//zhangsan 18
for(let [key,value ]of mapList.entries()){
console.log(key,value);
}
//name zhangsan
//age 18
- forEach
let mapList = new Map(
[['name','zhangsan'],
['age',18]]
);
mapList.forEach(function(value,key){
console.log(value,key);
})
//zhangsan name
//18 "age"
需要注意的是map的key完全可以是引用類型
let mapList = new Map();
let obj = {};
mapList.set(obj,{name:'zhangsan'});
console.log(mapList.get(obj));//{name:'zhangsan'}
4 WeakMap
map的閹割版衡查,鍵只能為引用類型用僧,沒有size屬性,沒有clear方法辰如,不能遍歷
ES6總篇--目錄