Weird behavior of Map()
P粉221046425
P粉221046425 2024-04-03 15:40:52
0
1
501

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粉221046425
P粉221046425

reply all(1)
P粉680087550

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template