[英]Why do I have to access my object property with the bracket annotation
So I have this object called items所以我有这个 object 称为项目
And I want to access the columnOrder property我想访问 columnOrder 属性
Why do I have to access it like this为什么我必须这样访问它
for (let item in items ) {
console.log(items[item].columnOrder)
}
and can't do不能做
for (let item in items ) {
console.log(items.item.columnOrder)
}
The reason for this is for accessing the value fo the dynamic object property we have to use bracket []
notation, as using dot notation will simply return undefined
as shown below.这样做的原因是为了访问动态 object 属性的值,我们必须使用方括号[]
表示法,因为使用点表示法将简单地返回undefined
,如下所示。
For example:例如:
var myCar = { make: 'Ford', model: 'Mustang', year: 1969 }; console.log( myCar['make'] ) console.log( myCar.make )
Here bracket []
notation is working as we are passing the object property as a string and also dot notation is working as we have passed exact object key make
which exits on the object.这里括号[]
表示法正在工作,因为我们将 object 属性作为字符串传递,并且点表示法也在工作,因为我们已经传递了在make
上退出的精确 object 密钥。
But if we store the key in a variable and try to use the bracket and dot notation, here is what happens:但是,如果我们将键存储在变量中并尝试使用方括号和点表示法,则会发生以下情况:
var myCar = { make: 'Ford', model: 'Mustang', year: 1969 }; var propertyName = 'make'; console.log( myCar[propertyName] ) console.log( myCar.propertyName )
You can see bracket notation worked as all keys in the square bracket notation are converted to string unless they're Symbols, since JavaScript object property names (keys) can only be strings or Symbols.您可以看到方括号表示法中的所有键都转换为字符串,除非它们是符号,因为 JavaScript object 属性名称(键)只能是字符串或符号。 Thus myCar[propertyName]
is evaluated as myCar['make']
which gives the correct result.因此myCar[propertyName]
被评估为myCar['make']
,它给出了正确的结果。
But with dot notation, it simply means that you are trying to access an unassigned property of myCar
object, which will always return undefined
.但是使用点表示法,它仅仅意味着您正在尝试访问myCar
object 的未分配属性,该属性将始终返回undefined
。
In your case, as you are using:在您的情况下,当您使用时:
items.item.columnOrder
This results in an error like:这会导致如下错误:
Uncaught TypeError: Cannot read property 'columnOrder' of undefined未捕获的类型错误:无法读取未定义的属性“columnOrder”
as you are trying to access columnOrder
from undefined
.当您尝试从undefined
访问columnOrder
时。
Dashes are not allowed because it will get interpreted as the subtraction operator.不允许使用破折号,因为它将被解释为减法运算符。 Similar post: Are dashes allowed in javascript property names?类似的帖子: javascript 属性名称中是否允许使用破折号?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.