2

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.

2 Answers 2

4

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));

Sign up to request clarification or add additional context in comments.

2 Comments

@mplungjan - If you want to view the map, you can look at the browser's console.
Look at the browser's console, or use m.entries() to see [key, value] pairs
1

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.