考虑下面的例子:
a={
'firstProperty': "first",
'secondProperty':"second"
};
console.log(a[[[["firstProperty"]]]]);
通过使用多括号表示法,我可以访问 firstProperty。括号符号如何访问此属性?
考虑下面的例子:
a={
'firstProperty': "first",
'secondProperty':"second"
};
console.log(a[[[["firstProperty"]]]]);
通过使用多括号表示法,我可以访问 firstProperty。括号符号如何访问此属性?
您正在使用嵌套数组,并且通过使用非字符串或符号作为值,该值将转换为字符串。
console.log([[["firstProperty"]]].toString());
因为您在属性访问器表达式中作为键提供的内容如果不是符号或字符串,则会转换为字符串。console.log(a[[[["firstProperty"]]]]);使用数组数组作为访问器表达式中的属性名称。由于这不是符号,因此将其转换为字符串。当您将数组转换为字符串时,您会得到字符串,"firstProperty"因为它是这样Array.prototype.toString工作的:
console.log(String([[["firstProperty"]]]));
...并"firstProperty"正确识别对象中的属性之一,因此属性访问器表达式为您提供该属性的值。
使用这样的数组是不必要的。只需使用
console.log(a["firstProperty"]);
或者
console.log(a.firstProperty);