Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

95.ES6 之 Map #95

Open
neptoo opened this issue Dec 4, 2019 · 0 comments
Open

95.ES6 之 Map #95

neptoo opened this issue Dec 4, 2019 · 0 comments

Comments

@neptoo
Copy link
Owner

neptoo commented Dec 4, 2019

Map

JavaScript 默认对象是{ },是一组键值对。键要求必须是字符串,而值可以是其他类型,甚至键必须是唯一的,因为当键不唯一时,后面的键会覆盖前面的键。

  • Object键为string类型,Map的键是任意类型
  • 手动计算Object尺寸,Map.size可以获取尺寸
let key1 = 12;
let value1 = 'mini';
let m1 = new Map([[key1, value1]]); // Map(1) {12 => "mini"}

let m2 = new Map([['Li', 'Bai'],['Du','Fu']]);
console.log(m2.size); // 2

5种操作

set增加

let m10 = new Map();
m10.set('Libai', 24);
m10.set('Libai', 28);  
console.log(m10);  // Map(1) {"Libai" => 28}

get查找

let m11 = new Map([['Dufu',25]]);
m11.get('Dufu');  // 25

has(key)存在

let m12 = new Map([['Luyou','song'],['Wangwei','tang']]);
m12.has('Sushi');  // false
m12.has('Luyou');  // true

delete移除

let m13 = new Map([[2000,'Tang']]);
m13.delete(2000);
console.log(m13);  // Map(0){}

clear清空

m12.clear();
console.log(m12);  // Map(0){}

4种遍历

keys() 返回一个新的 Iterator 对象。它包含按照顺序插入 Map 对象中每个元素的key值。

let m2 = new Map([[12, 'yang'],['xing', 'hua']])
var iterator1 = m2.keys(); 
console.log(iterator1); //[Map Iterator] { 12, 'xing' }
console.log(iterator1.next().value); // 12
console.log(iterator1.next().value); // xing

values() 方法返回一个新的Iterator对象。它包含按顺序插入Map对象中每个元素的value值。

let m2 = new Map([[12, 'yang'],['xing', 'hua']])
console.log(m2.values()) // [Map Iterator] { 'yang', 'hua' }

entries() 方法返回一个新的包含 [key, value]的 Iterator对象,返回的迭代器的迭代顺序与 Map对象的插入顺序相同。

let m2 = new Map([[12, 'yang'],['xing', 'hua']])
var iterator1 = m2.entries(); 
console.log(iterator1); //[Map Iterator] { [ 12, 'yang' ], [ 'xing', 'hua' ] }

forEach() 方法将会以插入顺序对 Map 对象中的每一个键值对执行一次参数中提供的回调函数。

let Data = new Map();
let objKey = { num:10 };
let obj = {
  num:5
}
Data.set("a", 1);
Data.set("b", 2);
Data.set("c", 3);
Data.forEach(function (value,key) {
  console.log(value*this.num); // 输出5 10 15
}, obj)

阅读原文

你不知道的ES6系列: 增强版Array、Object之Set、Map数据结构

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant