Reputation: 97
I'm trying to create a map based on certain arrays of three. For example,
const rule30Map = new Map();
rule30Map.set([1, 0, 0], 1);
rule30Map.set([0, 1, 1], 1);
rule30Map.set([0, 1, 0], 1);
rule30Map.set([0, 0, 1], 1);
When I try getting a value based on values in an array, the console returns undefined,
console.log(rule30Map.get([1, 0, 0])); // prints undefined
but the expected output would be 1. Can somebody explain why my logic was misunderstood?
Upvotes: 1
Views: 809
Reputation: 76
You could do:
const a = [1,0,0];
const map = new Map();
map.set(a.toString(), "value");
map.get([1,0,0].toString());
I assume you are computing the [1,0,0] part.
Upvotes: 1
Reputation: 413856
The keys are compared with ===
comparison. Two separate arrays that look like [1, 0, 0]
are still two separate arrays that are not equal to each other.
Working out some automated way of keeping track of key objects by their characteristics somehow would probably be more complicated than using a plain object for storage. Because JavaScript does not provide a generic way for a class of objects to supply hashing and comparison overrides means that Map and Set in JavaScript are somewhat limited in usefulness.
Upvotes: 2