无法获取数字对象的键
Can't get key of object that is numeric
我正在使用 API 对象数组 returns。我可以得到所有的钥匙,但其中两个有数字作为钥匙,我无法得到它。给我一个错误。
我真的不知道为什么我拿不到那些钥匙。
数字有什么不同吗?
顺便说一句,我正在使用 axios。
如果您使用点表示法,则应更改为括号表示法以访问以数字开头的属性。
下面的代码使用点符号,会抛出错误
const test = {"1h" : "test value"};
console.log(test.1h); // error
为什么:
In the object.property syntax, the property must be a valid JavaScript
identifier.
An identifier is a sequence of characters in the code that identifies a variable, function, or property.
In JavaScript, identifiers are case-sensitive and can contain Unicode letters, $, _, and digits (0-9), but may not start with a digit.
下面的代码使用括号表示法,工作正常
const test = {"1h" : "test value"};
console.log(test["1h"]); // works
为什么:
In the object[property_name] syntax, the property_name is just a
string or Symbol. So, it can be any string, including '1foo', '!bar!',
or even ' ' (a space).
查看文档here
我正在使用 API 对象数组 returns。我可以得到所有的钥匙,但其中两个有数字作为钥匙,我无法得到它。给我一个错误。 我真的不知道为什么我拿不到那些钥匙。
数字有什么不同吗?
顺便说一句,我正在使用 axios。
如果您使用点表示法,则应更改为括号表示法以访问以数字开头的属性。
下面的代码使用点符号,会抛出错误
const test = {"1h" : "test value"};
console.log(test.1h); // error
为什么:
In the object.property syntax, the property must be a valid JavaScript identifier.
An identifier is a sequence of characters in the code that identifies a variable, function, or property.
In JavaScript, identifiers are case-sensitive and can contain Unicode letters, $, _, and digits (0-9), but may not start with a digit.
下面的代码使用括号表示法,工作正常
const test = {"1h" : "test value"};
console.log(test["1h"]); // works
为什么:
In the object[property_name] syntax, the property_name is just a string or Symbol. So, it can be any string, including '1foo', '!bar!', or even ' ' (a space).
查看文档here