简体   繁体   中英

Using integer keys with dot notation to access property in javascript objects

Why can't we use integer keys in dot expression to access property values ?

var obj = {1: 'one', two: '2'}
console.log(obj.1) // error
console.log(obj.two)

In case of dot notation to access a value, the property key must be a valid identifier

In this code, property must be a valid JavaScript identifier, ie a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. For example, object.$1 is valid, while object.1 is not.

You can use bracket notation in this case

obj['1']

Spec: Property Accessors

Adding to @Arun P Johny' s answer we can use obj['1'] with quotes or obj[1] without quotes in case of integer. where as accessing obj['two'] will work but obj[two] will throw an error if there is no variable/constant as two .

It is a JavaScript base princible which says variables cannot start with a number. Over here the property is a variable and hence it cannot start with a number.

You can check more about variable definition rules here

Hope this helps.

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