数组作为JavaScript映射的键? [英] Array as a javascript map's key?

查看:72
本文介绍了数组作为JavaScript映射的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Map是ECMA6中的新对象,如果将多个值分配给同一键,它将覆盖所有先前的值。例如,

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.

推荐答案

在JavaScript中,数组,对象或函数是引用类型,当您比较它们时,您实际上所做的是比较对它们在内存中位置的引用,而不是对其值的引用。当它们都分配给不同的位置时,结果将返回 false。

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".

您应该做的是将它们转换为原始类型。 JSON字符串,例如:

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

这篇关于数组作为JavaScript映射的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆