search

Home  >  Q&A  >  body text

Weird behavior of Map()

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 when I want to get the value not through the name of the key variable but through the value [1,2], there is no such thing If you add like this

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

About the map

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"

P粉221046425P粉221046425230 days ago447

reply all(1)I'll reply

  • P粉680087550

    P粉6800875502024-04-04 13:33:56

    Use the === operator to compare keys. Arrays are objects, and === compares references to objects, not their values. [1, 2] === [1, 2] returns false because each object/array literal creates a new reference to the new object. This is why

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

    Insert three values ​​using three different keys and why

    m.get([1,2])

    Return undefined.

    reply
    0
  • Cancelreply