How can i make Map.has() work with arrays?
Why does this example output false?
let test = new Map();
test.set(["a", "b"], "hi");
console.log(test.has(["a", "b"]));
How can i make Map.has() work with arrays?
Why does this example output false?
let test = new Map();
test.set(["a", "b"], "hi");
console.log(test.has(["a", "b"]));
It doesn't work because your two arrays are not referring to the same object. The array contents are identical, but the arrays themselves are not.
It will work if you use the same object to both set and retrieve the value:
let test = new Map();
let key = ["a", "b"];
test.set(key, "hi");
console.log(test.has(key)); // true
Key equality is based on the
sameValueZero algorithm
:NaN
is considered the same asNaN
(even though NaN !== NaN) and all other values are considered equal according to the semantics of the === operator. In the current ECMAScript specification -0 and +0 are considered equal, although this was not so in earlier drafts. See "Value equality for -0 and 0" in the Browser compatibility table for details.
Since in JS comparing two references will never turn out to be true, so you need to store reference of key in some variable and use when checking on Map again
console.log([] === [])
console.log({} === {})
let test = new Map();
let key = ["a","b"]
test.set(key, "hi");
console.log(test.has(key));