当我们需要进行一些键值对数据的存储时,js 本身普通对象可以完成这个过程,es6 中提供了一个新的数据结构叫做 Map
二者之间性能差距有多大呢
const map = {};
// insert key-value-pair
map["key1"] = "value1";
map["key2"] = "value2";
map["key3"] = "value3";
// check if map contians key
if (map.hasOwnProperty("key1")) {
console.log("Map contains key1");
}
// get value with specific key
console.log(map["key1"]);
这种做法很常见,但同时也有很大的局限
在 js 中,当你使用对象 object 时, 键 key 只能有 string 和 symbol 。然而 Map 的 key 支持的就比较多了,可以支持 string, symbol, number, function, object, 和 primitives
const map = new Map();
const myFunction = () => console.log("I am a useful function.");
const myNumber = 666;
const myObject = {
name: "plainObjectValue",
otherKey: "otherValue",
};
map.set(myFunction, "function as a key");
map.set(myNumber, "number as a key");
map.set(myObject, "object as a key");
console.log(map.get(myFunction)); // function as a key
console.log(map.get(myNumber)); // number as a key
console.log(map.get(myObject)); // object as a key
const map = new Map();
map.set(‘someKey1‘, 1);
map.set(‘someKey2‘, 1);
...
map.set(‘someKey100‘, 1);
console.log(map.size) // 100, Runtime: O(1)
const plainObjMap = {};
plainObjMap[‘someKey1‘] = 1;
plainObjMap[‘someKey2‘] = 1;
...
plainObjMap[‘someKey100‘] = 1;
console.log(Object.keys(plainObjMap).length) // 100, Runtime: O(n)
const map = new Map();
map.set(‘someKey1‘, 1);
map.set(‘someKey2‘, 2);
map.set(‘someKey3‘, 3);
for (let [key, value] of map) {
console.log(`${key} = ${value}`);
}
// someKey1 = 1
// someKey2 = 2
// someKey3 = 3
const plainObjMap = {};
plainObjMap[‘someKey1‘] = 1;
plainObjMap[‘someKey2‘] = 2;
plainObjMap[‘someKey3‘] = 3;
for (let key of Object.keys(plainObjMap)) {
const value = plainObjMap[key];
console.log(`${key} = ${value}`);
}
// someKey1 = 1
// someKey2 = 2
// someKey3 = 3
map 是保证顺序的,按照添加的顺序依次出来的。
原文:https://www.cnblogs.com/geck/p/13610410.html