JavaScript Map 和 Set
结论
Map存储键值对,读取时与插入顺序一致。 var map = new Map([[1, "1"], [3, "3"], [2, "2"]]);
map.set("foo", "bar");
for (const [key, val] of map) {
console.log(key, val);
}
输出: 任何值,对象或原始值,都可作为 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 () {}
相比 同时还自带一些便捷的属性和方法,比如 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);
}
输出: 相关资源 |
正文到此结束