es6中的Map和Set,for ... of

Map是一组键值对的结构,具有极快的查找速度。得到的是一个对象。

var m = new Map([['Michael', 95], ['Bob', 75], ['Tracy', 85]]);
var a = [['Michael', 95], ['Bob', 75], ['Tracy', 85]];
console.log(m)
console.log(a)

这里写图片描述

// Map的增删改查
var m = new Map(); // 空Map
m.set('Adam', 67); // 添加新的key-value
m.set('Bob', 59);
m.has('Adam'); // 是否存在key 'Adam': true
m.get('Adam'); // 67
m.delete('Adam'); // 删除key 'Adam'
m.get('Adam'); // undefined

Set和Map类似,也是一组key的集合,但不存储value

var s1 = new Set(); // 空Set
var s2 = new Set([1, 2, 3]); // 含1, 2, 3
console.log(s1)
console.log(s2)

这里写图片描述

重复元素自动过滤

var s = new Set([1, 2, 3, 3, '3']);
console.log(s)
==》 {1, 2, 3, "3"}

add(key)和delete(key)

s.add(4);
s; // Set {1, 2, 3, 4}
s.delete(4);
s; // Set {1, 2, 3}

for … of

ES6标准引入了新的iterable类型,Array、Map和Set都属于iterable类型,对于这种类型用for…of进行遍历

var a = ['A', 'B', 'C'];
var s = new Set(['A', 'B', 'C']);
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
for (var x of a) { // 遍历Array
    console.log(x);
}
for (var x of s) { // 遍历Set
    console.log(x);
}
for (var x of m) { // 遍历Map
    console.log(x[0] + '=' + x[1]);
}

forEach()
更好的方式是直接使用iterable内置的forEach方法

var a = ['A', 'B', 'C'];
a.forEach(function (element, index, array) {
    // element: 指向当前元素的值
    // index: 指向当前索引
    // array: 指向Array对象本身
    console.log(element + ', index = ' + index);
});
var s = new Set(['A', 'B', 'C']);
s.forEach(function (element, sameElement, set) {
    console.log(element);
});
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
m.forEach(function (value, key, map) {
    console.log(value);
});

猜你喜欢

转载自blog.csdn.net/xuxu_qkz/article/details/80318661