Aaron Chen
Aaron Chen

Reputation: 31

Array as a javascript map's key?

Map is a new object in ECMA6, if assign multiple value to the same key, it will overwrite all previous values. For example,

'use strict';

var m = new Map();

m.set(['aaron', 100]);
m.set(['aaron', 100], 1);
m.set(['aaron', 100], 10);
m.set(['aaron', 100], 100);
m.set(['aaron', 100], 1000);
m.set(['aaron', 100], 10000);

console.log(m.get(['aaron', 100]));

It will show a weird output(undefined), why? Many thanks.

Upvotes: 2

Views: 551

Answers (2)

Thien
Thien

Reputation: 48

In JavaScript, Array, Object or Function are Reference types, when you compare them what you actually do is comparing the references to their locations in memory, not their values. As they both allocated to difference locations, the result will return "false".

What you should do is convert them into a primitive type. JSON string for example:

let a = {1: 'foo'},
    b = {1: 'foo'};
    
console.log(a === b);
console.log(JSON.stringify(a) == JSON.stringify(b));

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191976

The Map uses as the key the reference to the array, and not the contents of the array.

This simple comparison shows that arrays with the same content, are not the same array (have different reference):

const a = ['aaron', 100];
const b = ['aaron', 100];

console.log(a === b);

It works if you set and get the same reference:

const arr = ['aaron', 100];
const m = new Map();
m.set(arr);
m.set(arr, 1);
m.set(['aaron', 100], 10);
m.set(['aaron', 100], 100);
m.set(['aaron', 100], 1000);
m.set(['aaron', 100], 10000);

console.log(m.get(arr));

Upvotes: 4

Related Questions