Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Map.has() return false for an Integer key that does exist?

I have a map that consists of several key : value pairs, and the keys are all integers (that are then of course stored as strings).

However, I can't use Map.prototype.has("1") nor Map.prototype.has(1) to confirm a key exists within the map. How do I go about doing this? I want to use the Map.prototype.has() method in order to avoid the whole 0 is false problem.

let map = new Map();
map[1] = 2;
console.log(map); //Map { 1: 2 }
console.log(map.has("1")); //false
console.log(map.has(1)); //false
like image 894
dehuff Avatar asked Dec 30 '22 15:12

dehuff


1 Answers

Use Map.prototype.set not map[1] = 2. Maps are Objects with their own set of rules, so you cannot set it the way above. Learn more here.

let map = new Map();
map.set(1,2);
console.log(map); // Map(1) { 1 => 2 }
console.log(map.has("1")); //false
console.log(map.has(1)); //true
like image 52
quicVO Avatar answered Jan 02 '23 05:01

quicVO