[英]Are array keys implicitly coerced to numbers?
I'm in the book, This & Object Prototypes, Chapter 3: Objects. 我在书中, 这个和对象原型,第3章:对象。
In the arrays section, the author says if you add a property to an array, but the array looks like a number, it will end up as part of the array index: 在数组部分,作者说如果向数组添加属性,但数组看起来像数字,它将最终作为数组索引的一部分:
myArray["3"] = "baz";
console.log(myArray.length);
console.log(myArray[3]);
It looks like JavaScript is implicitly coercing the "3" string into the number 3, then it's saying place "baz" in index 3 of the array. 看起来JavaScript隐含地将“3”字符串强制转换为数字3,然后它就是将“baz”放在数组的索引3中。
Actually, it's the other way around. 实际上,这是相反的方式。 All keys in JavaScript objects are strings , and arrays are objects. JavaScript对象中的所有键都是字符串 ,而数组是对象。 That means myArray[3]
is the same as myArray["3"]
because all keys, if not already strings, are coerced into strings because all JavaScript object keys are strings . 这意味着myArray[3]
与myArray["3"]
相同, 因为所有键(如果不是字符串)都被强制转换为字符串,因为所有JavaScript对象键都是字符串 。 Per MDN : 每个MDN :
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. 对象属性名称可以是任何有效的JavaScript字符串,也可以是可以转换为字符串的任何内容,包括空字符串。
And: 和:
Please note that all keys in the square bracket notation are converted to String type, since objects in JavaScript can only have String type as key type. 请注意,方括号表示法中的所有键都将转换为String类型,因为JavaScript中的对象只能将String类型作为键类型。 For example, in the above code, when the key
obj
is added to themyObj
, JavaScript will call theobj.toString()
method, and use this result string as the new key. 例如,在上面的代码中,当键obj
被添加到myObj
,JavaScript将调用obj.toString()
方法,并使用此结果字符串作为新键。
For example: 例如:
const obj = {
toString() {
return 'foobar';
}
};
const anotherObj = {};
anotherObj[obj] = 'baz';
//anotherObj.foobar is now 'baz'
Since obj
is converted to a string implicitly, obj.toString
is called which returns 'foobar'
, which is used as the key value. 由于obj
被隐式转换为字符串, obj.toString
调用obj.toString
,返回'foobar'
,用作键值。 The same applies for arrays -- when using bracket notation. 这同样适用于数组 - 使用括号表示法时。 All keys are strings, and accessing using bracket notation coerces the expression in the brackets into a string. 所有键都是字符串,使用括号表示法访问将括号中的表达式强制转换为字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.