admin管理员组文章数量:1353331
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)
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)
Share
Improve this question
asked Apr 27, 2015 at 6:01
bilal_azambilal_azam
4,8104 gold badges38 silver badges69 bronze badges
2
- 3 I think due to the limitation of naming convention of javascript variable. – Abhisek Malakar Commented Apr 27, 2015 at 6:03
- 1 is represented as string internally. – bilal_azam Commented Apr 27, 2015 at 6:06
3 Answers
Reset to default 13In 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, i.e. 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.
本文标签: Using integer keys with dot notation to access property in javascript objectsStack Overflow
版权声明:本文标题:Using integer keys with dot notation to access property in javascript objects - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743920865a2562065.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论