简体   繁体   中英

Why do I have to access my object property with the bracket annotation

So I have this object called items

在此处输入图像描述

And I want to access the columnOrder property

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.

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.

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. Thus myCar[propertyName] is evaluated as myCar['make'] which gives the correct result.

But with dot notation, it simply means that you are trying to access an unassigned property of myCar object, which will always return 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

as you are trying to access columnOrder from undefined .

Dashes are not allowed because it will get interpreted as the subtraction operator. Similar post: Are dashes allowed in javascript property names?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM