简体   繁体   English

JavaScript在对象键值对中删除数组括号

[英]JavaScript drops Array Brackets in Object Key value pair

Hey guys I noticed something strange today with trying to set a key value pair in JavaScript. 大家好,我今天发现尝试在JavaScript中设置键值对有些奇怪。 I know that The Key of an object is always 'stringified' so that the key value pair is always string: value, however something strange happened today when I tried this with an array. 我知道对象的键始终是“字符串化的”,因此键值对始终是字符串:值,但是今天当我使用数组尝试时,发生了一些奇怪的事情。 Example below: 下面的例子:

var ob = {}; 

var a = [2,4]; 

ob[a] = 10; 

console.log("this is ob ", ob);

Here I have tried adding the key [2,4] to map to 10. However, the console log returns the string 2,4 mapping to 10 instead of the string [2,4] mapping to 10. Does anyone know why this happens? 在这里,我尝试添加键[2,4]映射到10。但是,控制台日志返回的字符串2,4映射到10,而不是字符串[2,4]映射到10。 ?

Using an object or an array as the property name, doesn't invoke JSON#stringify , but the object's toString method, which in arrays returns the array elements joined by a comma. 使用对象或数组作为属性名称,不会调用JSON#stringify ,而是对象的toString方法,该方法在数组中返回以逗号连接的数组元素。

In the example I override the Array#toString method, and you can see that the resulting property name reflects that: 在示例中,我重写了Array#toString方法,您可以看到生成的属性名称反映了这一点:

 var ob = {}; var a = [2,4]; a.toString = function() { return 'cats' }; // override toString ob[a] = 10; console.log("this is ob ", ob); 

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

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