Map:
初始化:
const mapSize = (new Map()).size; // mapSize: 0
const pair1 = [1, ‘one‘];
const pair2 = [2, ‘two‘];
const map = new Map([pair1, pair2]); // new Map().set(...pair1).set(...pair2);
// 以最后设的值为准:
const pair1 = [1, ‘one‘];
const pair2 = [1, ‘uno‘];
const pair3 = [1, ‘eins‘];
const pair4 = [2, ‘two‘];
const map = new Map([pair1, pair2, pair3, pair4]); // new Map().set(...pair3).set(...pair4);
let map = new Map();
const obj = {x: 1, y: 2};
const keys = Object.keys(obj);
keys.forEach(key => map.set(key, obj[key]));
set, get, has:
let map = new Map();
map.set(‘key‘, ‘value‘); // set可以连用哦
const value = map.get(‘key‘);
可以使用任何东西做key哦:
let map = new Map();
const obj = {};
map.set({}, ‘object is key‘);
还有has方法:
let map = new Map([[‘key‘, ‘VALUE‘]]);
const hasKey = map.has(‘key‘);
keys与values方法:
let map = new Map();
map.set(1, ‘one‘).set(2, ‘two‘);
assert.deepEqual([...map.keys()], [1,2]);
assert.deepEqual([...map.values()], [‘one‘, ‘two‘]);