Why should I use Map () when the key is unknown before starting?

The MDN documentation Mapsays:

If you still don’t know which one to use [the object or map], ask yourself the following questions:

  • Are keys usually unknown before launch, do you need to dynamically look for them?

  • [...]

All these are signs that you need a card for the collection. [...] https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

But I can also set keys for dynamic objects with square brackets (i.e. myObject[dynamicKey]).

Is there any other reason to use mapswhen I have dynamic keys other than how to "set the" Map "target as a collection?

+4
source share
4 answers

The reason for using Mapwith arbitrary keys is to avoid name collisions. For instance. with a simple object:

let a = {};

function foo(key) {
  console.log(a[key] === undefined ? "Unset" : "Set");
  a[key] = "Hi";
  console.log(a[key]);
  console.log("" + a);
}

foo("goodKey");  // Unset, Hi, [object Object]
foo("toString"); // Set, Hi, TypeError: can't convert a to primitive type
Run codeHide result

Above we came across Object.prototype.toString.

Since Mapwe are in order:

let a = new Map();

function foo(key) {
  console.log(a.get(key) === undefined ? "Unset" : "Set");
  a.set(key, "Hi");
  console.log(a.get(key));
  console.log("" + a);
}

foo("goodKey");  // Unset, Hi, [object Map]
foo("toString"); // Unset, Hi, [object Map]
Run codeHide result
+2
source

This is due to an earlier point in the same document:

The object has a prototype, so there are default keys on the map.

Traditionally, when you iterate through an object (this is what they mean with “look [keys] up dynamically”), you need to filter the properties of the prototype:

for( var key in obj ) {
    if( obj.hasOwnProperty(key) ) {
        // do something
    }
}

When you iterate over a map, you can skip the additional check because it does not have its own properties mixed with the properties of the prototype.

+1

. . , , . .

, Map, ECMAScript 6 ECMAScript 5. polyfill, , .

+1

. , .

:

let author1 = { name: "Name1" };
let author2 = { name: "Name2" };

let mostRecentReply = {};

mostRecentReply[author1] = "Test1";
mostRecentReply[author2] = "Test2";

console.log( mostRecentReply[author1] );
console.log( mostRecentReply[author2] );

:

Test2
Test2

:

let mostRecentReply = new Map();
mostRecentReply.set(author1, "Test1");
mostRecentReply.set(author2, "Test2");

console.log( mostRecentReply.get(author1) );
console.log( mostRecentReply.get(author2) );

:

Test1
Test2
0

Source: https://habr.com/ru/post/1663365/


All Articles