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);
});