var myMap = new Map();
var keyString = 'a string',
keyObj = {},
keyFunc = function() {};
// setting the values
myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, 'value associated with keyObj');
myMap.set(keyFunc, 'value associated with keyFunc');
myMap.size; // 3
// getting the values
myMap.get(keyString); // "value associated with 'a string'"
myMap.get(keyObj); // "value associated with keyObj"
myMap.get(keyFunc); // "value associated with keyFunc"
myMap.get('a string'); // "value associated with 'a string'"
// because keyString === 'a string'
myMap.get({}); // undefined, because keyObj !== {}
myMap.get(function() {}); // undefined, because keyFunc !== function () {}
知识兔相比 Object
,除了对可作为键的值没要求外,Map
自带遍历器(iterator),可对其使用 for of
语句。
同时还自带一些便捷的属性和方法,比如 size
,clear()
。
Set
存储唯一的值,对于重复的值会被忽略。
示例:
var obj = { a: 1, b: 2 };
var set = new Set([1, 2, 2, "foo"]);
set.add(obj);
set.add(obj);
console.log("size:", set.size);
console.log(set.has(2));
console.log(set.has(obj));
for (const val of set) {
console.log(val);
}
知识兔输出:
4
true
true
1
2
foo
{ a: 1, b: 2 }
知识兔相关资源