[英]How bracket notation in javascript access the property of an object?
Consider below example:考虑下面的例子:
a={
'firstProperty': "first",
'secondProperty':"second"
};
console.log(a[[[["firstProperty"]]]]);
by using multiple bracket notation i am able to access the firstProperty.通过使用多括号表示法,我可以访问 firstProperty。 How bracket notation is accessing this property??
括号符号如何访问此属性?
You are using a nested array and by using a non string or symbol as value, the value is converted to string.您正在使用嵌套数组,并且通过使用非字符串或符号作为值,该值将转换为字符串。
console.log([[["firstProperty"]]].toString());
Because what you provide as the key in a property accessor expression is converted to string if it isn't a Symbol or a string.因为您在属性访问器表达式中作为键提供的内容如果不是符号或字符串,则会转换为字符串。
console.log(a[[[["firstProperty"]]]]);
uses an array of arrays as the property name in the accessor expression.使用 arrays 数组作为访问器表达式中的属性名称。 Since that isn't a Symbol, it's converted to string.
由于这不是符号,因此将其转换为字符串。 When you convert your array to string, you get the string
"firstProperty"
because that's how Array.prototype.toString
works:当您将数组转换为字符串时,您会得到字符串
"firstProperty"
,因为Array.prototype.toString
就是这样工作的:
console.log(String([[["firstProperty"]]]));
...and "firstProperty"
correctly identifies one of the properties in the object, so the property accessor expression gives you the value of that property. ...并且
"firstProperty"
正确标识了 object 中的一个属性,因此属性访问器表达式为您提供了该属性的值。
Using an array like that is unnecessary.使用这样的数组是不必要的。 Just use
只需使用
console.log(a["firstProperty"]);
or或者
console.log(a.firstProperty);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.