-4
 let key = [1,2]
 let m = new Map()
 m.set(key, "12")
 console.log(m.get(key))  // 12
 console.log(m.get([1,2]))  // undefined

Why is it that when I want to get a value not by the name of the key variable but by the value [1,2], there is no such thing And if you add so

 m.set([1,2], "12")
 m.set([1,2], "123")
 m.set([1,2], "1234")

about the map will be

Map(4) { (2) […] → "12", (2) […] → "12", (2) […] → "123", (2) […] → "1234" }​
size: 4​
<entries>​​
0: Array [ 1, 2 ] → "12"​​
1: Array [ 1, 2 ] → "12"​​
2: Array [ 1, 2 ] → "123"​​
3: Array [ 1, 2 ] → "1234"
AO-
  • 1
  • 1
  • 1
    That's because `[1, 2] === [1, 2]` returns `false`. Objects are compared by reference and each object literal (arrays are objects) creates a new reference to a new object. – jabaa May 05 '23 at 14:41
  • 1
    This question is currently closed with the reason that it was not written in English. An edit has since resolved that. But the question should probably be marked as a duplicate of [Using Array objects as key for ES6 Map](https://stackoverflow.com/questions/32660188/using-array-objects-as-key-for-es6-map) – Wyck May 05 '23 at 14:48
  • there is an opportunity to use an object as a key, but there is no way to get a value from this key? – AO- May 05 '23 at 14:49
  • Arrays are not values. They're objects. Two different arrays that happen to contain the same elements are still, in fact, different arrays. You're confusing yourself because although it may appear, because you're using an array literal, that `[1,2]` is "the same value" as some other `[1,2]` elsewhere in your code, **it's not**. Each `[1,2]` literal becomes its own array object and they are therefore not the same key. – Wyck May 05 '23 at 14:53
  • There are multiple ways to get the values. You can store the key objects/arrays use them or you can first get the keys from the map. – jabaa May 05 '23 at 14:54
  • how does it make sense then to use an object as keys ? – AO- May 05 '23 at 14:54
  • You've showed it in your first snippet. Either store the reference or get the reference from the map with [`Map.prototype.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys) – jabaa May 05 '23 at 14:55

1 Answers1

0

Keys are compared using === operator. Arrays are objects and === compares the references of objects, not their values. [1, 2] === [1, 2] returns false because each object/array literal creates a new reference to a new object. That's the reason why

m.set([1,2], "12")
m.set([1,2], "123")
m.set([1,2], "1234")

inserts three values with three different keys and why

m.get([1,2])

returns undefined.

jabaa
  • 5,844
  • 3
  • 9
  • 30