[英]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.
在此代码中,属性必须是有效的JavaScript标识符,即,一个字母数字字符序列,还包括不能以数字开头的下划线(“ _”)和美元符号(“ $”)。 For example, object.$1 is valid, while object.1 is not.
例如,object。$ 1有效,而object.1无效。
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.添加到@Arun P Johny 的答案中,我们可以使用带引号的
obj['1']
或在整数情况下不带引号的obj[1]
。 where as accessing obj['two']
will work but obj[two]
will throw an error if there is no variable/constant as two .其中 as 访问
obj['two']
将起作用,但obj[two]
如果没有变量/常量 as two将抛出错误。
It is a JavaScript base princible which says variables cannot start with a number. 它是JavaScript的基础,它表示变量不能以数字开头。 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. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.