简体   繁体   English

javascript 中的括号符号如何访问 object 的属性?

[英]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.

相关问题 在angular中,如何通过模板内的括号表示法访问对象属性? - In angular, how to access object property via bracket notation inside templates? 使用括号符号访问Javascript对象的属性 - Accessing a property of a Javascript object with bracket notation 使用Java括号表示法来访问存储在另一个变量中的属性/键 - Javascript bracket notation to access a property/key stored in another variable 使用括号符号(带有变量)访问对象属性的好处 - Benefit of using bracket notation (with variables) to access a property of an object 无法通过括号变量表示法访问对象属性 - unable to access object property through bracket variable notation 使用带有变量的括号表示法来访问 object 属性返回未定义 - Using bracket notation with a variable to access object property returns undefined Javascript对象括号表示法和requirejs - Javascript object bracket notation and requirejs JavaScript中带括号表示法的对象方法 - Object methods in JavaScript with bracket notation 实现一个函数来访问对象的属性,而不是使用点符号或方括号符号来访问属性? - Implementing a function to access an object's property versus accessing the property using dot notation, or bracket notation? 在 JavaScript 中,是否有任何方法可以在不使用点符号或括号符号的情况下获取 object 的属性? - In JavaScript, do there exist any ways to get a property of an object without using dot notation or bracket notation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM