es6 map members are unique. The new Map data structure in ES6 is similar to an object. The key value is not limited to strings and the member values are unique. The Map structure provides "value-value" correspondence and is a more complete Hash structure implementation. Map objects store key-value pairs and remember the original insertion order of keys; any value (object or primitive) can be used as a key or a value.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
Map and Set are both new data structures in ES6
Map is similar to an object, the key value is not limited to strings, and the member values are unique.
Set is similar to an array, with unique member values.
ES6 provides the Map data structure. It is similar to an object and is also a collection of key-value pairs, but the scope of "key" is not limited to strings. Various types of values (including objects) can be used as keys. In other words, the Object structure provides "string-value" correspondence, and the Map structure provides "value-value" correspondence, which is a more complete implementation of the Hash structure. If you need a "key-value" data structure, Map is more suitable than Object.
Map objects save key-value pairs and are able to remember the original insertion order of keys.
Any value (object or primitive) can be used as a key or a value.
Map is a new data structure introduced in ES6, please refer to ES6 Map and Set.
The key of an Object can only be a string or Symbols, but a Map The keys can be any values.
The key values in the Map are ordered (FIFO principle), but the keys added to the object are not.
Official explanation about objects being unordered: 1.An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method. 2. Chrome Opera’s JavaScript parsing engine follows the new ECMA-262 fifth edition specification. Therefore, when using a for-in statement to traverse object properties, the traversal order is not the property construction order. And JavaScript for IE6 IE7 IE8 Firefox Safari The parsing engine follows the older ECMA-262 third edition specification, and the order of attribute traversal is determined by the order in which the attributes are constructed.
The number of key-value pairs of Map can be obtained from the size attribute, while the number of key-value pairs of Object can only be calculated manually.
Object has its own prototype, and the key names on the prototype chain may conflict with the key names you set on the object.
Map.prototype.size
– Returns the number of key/value pairs of the Map object . Map.prototype.clear()
– Remove all keys/values of the Map object right. Map.prototype.set()
– Set key-value pairs and return the Map object. Map.prototype.get()
– Returns the value corresponding to the key. If it does not exist, it returns undefined. Map.prototype.has()
– Returns a Boolean value used to determine whether the Map contains the value corresponding to the key. Map.prototype.delete()
– Delete the element in the Map. It returns true if the deletion is successful and false if it fails. The traversal order of Map is the insertion order.
Map.prototype.keys()
: Returns the traverser of key names. Map.prototype.values()
: Returns the traverser of key values. Map.prototype.entries()
: Returns a traverser of all members. Map.prototype.forEach()
: Traverse all members of Map. for of
Since there is iterable, you can also use this methodUse the Map type and new keyword to create a Map:
Not just arrays, anything with an Iterator interface and each member is an Data structure of two-element array So Set Map array can create Map
let map1 = new Map(); map1.set('123',123)
const m2 = new Map([['baz', 3]]);
const set = new Set([ ['foo', 1], ['bar', 2] ]); const m3 = new Map(set);
Note m3 === m2 //false
const m3 = new Map(m2);
The biggest difference from objects: Multiple types of keys
var myMap = new Map(); var keyString = "a string"; myMap.set(keyString, "和键'a string'关联的值");
var myMap = new Map(); var keyObj = {} myMap.set(keyObj, "和键 keyObj 关联的值");
var myMap = new Map(); var keyFunc = function () {} // 函数 myMap.set(keyFunc, "和键 keyFunc 关联的值");
var myMap = new Map(); myMap.set(NaN, "not a number");
keys() , values() , entries()Map 的遍历顺序就是插入顺序
const map = new Map([ ['F', 'no'], ['T', 'yes'], ]); for (let key of map.keys()) { console.log(key); } // "F" // "T" for (let value of map.values()) { console.log(value); } // "no" // "yes" for (let item of map.entries()) { console.log(item[0], item[1]); } // "F" "no" // "T" "yes" // 或者 for (let [key, value] of map.entries()) { console.log(key, value); } // "F" "no" // "T" "yes" // 等同于使用map.entries() for (let [key, value] of map) { console.log(key, value); }
使用扩展运算符可以快速转数组
const map = new Map([ [1, 'one'], [2, 'two'], [3, 'three'], ]); [...map.keys()] // [1, 2, 3] [...map.values()] // ['one', 'two', 'three'] [...map.entries()] // [[1,'one'], [2, 'two'], [3, 'three']] [...map] // [[1,'one'], [2, 'two'], [3, 'three']]
转为数组后,可以使用数组的map,filter方法
const map0 = new Map() .set(1, 'a') .set(2, 'b') .set(3, 'c'); const map1 = new Map( [...map0].filter(([k, v]) => k < 3) ); // 产生 Map 结构 {1 => 'a', 2 => 'b'} const map2 = new Map( [...map0].map(([k, v]) => [k * 2, '_' + v]) ); // 产生 Map 结构 {2 => '_a', 4 => '_b', 6 => '_c'}
const m = new Map(); const o = {p: 'Hello World'}; m.set(o, 'content') m.get(o) // "content" m.has(o) // true m.delete(o) // true m.has(o) // false m.clear()
(1)Map 转为数组
前面已经提过,Map 转为数组最方便的方法,就是使用扩展运算符(...
)。
const myMap = new Map() .set(true, 7) .set({foo: 3}, ['abc']); [...myMap] // [ [ true, 7 ], [ { foo: 3 }, [ 'abc' ] ] ] var outArray = Array.from(myMap);
(2)数组 转为 Map
将数组传入 Map 构造函数,就可以转为 Map。
new Map([ [true, 7], [{foo: 3}, ['abc']] ]) // Map { // true => 7, // Object {foo: 3} => ['abc'] // }
(3)Map 转为对象
如果所有 Map 的键都是字符串,它可以无损地转为对象。
function strMapToObj(strMap) { let obj = Object.create(null); for (let [k,v] of strMap) { obj[k] = v; } return obj; } const myMap = new Map() .set('yes', true) .set('no', false); strMapToObj(myMap) // { yes: true, no: false }
如果有非字符串的键名,那么这个键名会被转成字符串,再作为对象的键名。
(4)对象转为 Map
对象转为 Map 可以通过Object.entries()
。
let obj = {"a":1, "b":2}; let map = new Map(Object.entries(obj));
此外,也可以自己实现一个转换函数。
function objToStrMap(obj) { let strMap = new Map(); for (let k of Object.keys(obj)) { strMap.set(k, obj[k]); } return strMap; } objToStrMap({yes: true, no: false}) // Map {"yes" => true, "no" => false}
(5)Map 转为 JSON
Map 转为 JSON 要区分两种情况。一种情况是,Map 的键名都是字符串,这时可以选择转为对象 JSON。
function strMapToJson(strMap) { return JSON.stringify(strMapToObj(strMap)); } let myMap = new Map().set('yes', true).set('no', false); strMapToJson(myMap) // '{"yes":true,"no":false}'
另一种情况是,Map 的键名有非字符串,这时可以选择转为数组 JSON。
function mapToArrayJson(map) { return JSON.stringify([...map]); } let myMap = new Map().set(true, 7).set({foo: 3}, ['abc']); mapToArrayJson(myMap) // '[[true,7],[{"foo":3},["abc"]]]'
(6)JSON 转为 Map
JSON 转为 Map,正常情况下,所有键名都是字符串。
function jsonToStrMap(jsonStr) { return objToStrMap(JSON.parse(jsonStr)); } jsonToStrMap('{"yes": true, "no": false}') // Map {'yes' => true, 'no' => false}
但是,有一种特殊情况,整个 JSON 就是一个数组,且每个数组成员本身,又是一个有两个成员的数组。这时,它可以一一对应地转为 Map。这往往是 Map 转为数组 JSON 的逆操作。
function jsonToMap(jsonStr) { return new Map(JSON.parse(jsonStr)); } jsonToMap('[[true,7],[{"foo":3},["abc"]]]') // Map {true => 7, Object {foo: 3} => ['abc']}
var first = new Map([[1, 'one'], [2, 'two'], [3, 'three'],]); var second = new Map([[1, 'uno'], [2, 'dos']]); // 合并两个 Map 对象时,如果有重复的键值,则后面的会覆盖前面的,对应值即 uno,dos, three var merged = new Map([...first, ...second]);
var myMap1 = new Map([["key1", "value1"], ["key2", "value2"]]); var myMap2 = new Map(myMap1); console.log(original === clone); // 打印 false。 Map 对象构造函数生成实例,迭代出新的对象。
注意,只有对同一个对象的引用,Map 结构才将其视为同一个键。这一点要非常小心。
const map = new Map(); map.set(['a'], 555); map.get(['a']) // undefined
虽然NaN
不严格相等于自身,但 Map 将其视为同一个键。
let map = new Map(); map.set(NaN, 123); map.get(NaN) // 123
【相关推荐:javascript视频教程、编程视频】
The above is the detailed content of Are es6 map members unique?. For more information, please follow other related articles on the PHP Chinese website!