Map.prototype.size
size是可访问属性,返回Map对象的成员数量。
const map = new Map();
map.set('a', 'alpha');
map.set('b', 'beta');
map.set('g', 'gamma');
console.log(map.size); //3
Map.prototype.clear()
clear()
clear()会移除Map对象中的所有元素。
const map = new Map();
map.set('bar', 'baz');
map.set(1, 'foo');
console.log(map.size); //2
map.clear();
console.log(map.size); //0
Map.prototype.delete()
delete(key)
delete()可以移除Map对象中特定的元素,若Map对象中存在该元素则移除它并返回true;否则返回false。
const map = new Map();
map.set('bar', 'foo');
console.log(map.delete('bar'));// true
console.log(map); //Map(0) {size: 0}
console.log(map.has('bar')); // false
Map.prototype.entries()
entries()
entries()返回一个新的包含[key, value]对的Iterator对象,返回的迭代器的迭代顺序与Map对象的插入顺序相同。
const map = new Map();
map.set('0','foo');
map.set(1, 'bar');
const iterator = map.entries();
console.log(iterator.next().value); //["0", "foo"];
console.log(iterator.next().value); //[1, "bar"]
Map.prototype.forEach()
forEach()按照插入顺序依次对Map中每个键/值对执行一次给定的函数。
function logMapElements(value, key ,map) {
console.log(`m[${key}] = ${value}`);
}
new Map([['foo', 3], ['bar', {}], ['baz', undefined]]).forEach(logMapElements);
//"m[foo] = 3"
//"m[bar] = [object Object]"
//"m[baz] = undefined"
Map.prototype.get()
myMap.get(key);
get()方法返回某个Map对象中的一个指定元素。
const map = new Map();
map.set('baz', 'foo');
console.log(map.get('bar')); //"foo"
Map.prototype.has()
has(key)
has()返回一个布尔值,用来表明对象Map是否存在指定元素。
const map = new Map();
map.set("bar", "foo");
console.log(map.has("bar")); //true
console.log(map.has("baz")); //false
Map.prototype.keys()
keys()
keys()返回一个引用的Iterator对象。它包含按照顺序插入Map对象中每个元素的key值。
const map = new Map();
map.set('0', 'foo');
map.set(1, 'baz');
const iterator = map.keys();
console.log(iterator.next().value); //'0'
console.log(iterator.next().value); // 1
Map.prototype.set()
set(key, value)
set()为Map对象添加或更新一个指定键(key)和值(value)的键值对。
const map = new Map();
map.set('bar', 'foo');
console.log(map.get('bar')); //'foo';
console.log(map.get('baz')); //undefined;
Map.prototype.values()
values()
values()返回一个新的Iterator对象。它包含按顺序插入Map对象中每个元素的value值。
const map = new Map();
map.set('0', 'foo');
map.set(1, 'bar');
map.set({}, 'baz');
const iterator = map.values();
console.log(iterator.next().value); //"foo"
console.log(iterator.next().value); //"bar"
console.log(iterator.next().value); //"baz"