简体   繁体   English

"数组作为 javascript 地图的键?"

[英]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. Map 是 ECMA6 中的一个新对象,如果为同一个键分配多个值,它将覆盖所有以前的值。 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]));<\/code><\/pre>

It will show a weird output(undefined), why?它会显示一个奇怪的输出(未定义),为什么? Many thanks.非常感谢。

"

The Map uses as the key the reference to the array, and not the contents of the array. Map使用对数组的引用作为键,而不是数组的内容。

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

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.在 JavaScript 中,数组、对象或函数是引用类型,当您比较它们时,您实际上所做的是将引用与它们在内存中的位置进行比较,而不是它们的值。 As they both allocated to difference locations, the result will return "false".由于它们都分配到不同的位置,结果将返回“false”。

What you should do is convert them into a primitive type.您应该做的是将它们转换为原始类型。 JSON string for example: JSON字符串例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM