How to access object property beginning with a number (SyntaxError: Unexpected identifier)

余生长醉 提交于 2019-12-20 07:45:08

问题


I have an object within another object, which im trying to get the value but it always returns "unexpected identifier".

snow: Object {3h: 1.3}

console.log(data.snow.3h) //returns Uncaught SyntaxError: Unexpected identifier

console.log(data.snow) //returns Object {3h: 1.3}

So how can i get the value of 3h ?


回答1:


data.snow['3h'];

Properties accessed with dot notation can't begin with a number.

snow: Object {3h: 1.3} could be refactored to snow: {3h: 1.3}. It is redundant to type Object.

Also, if you wrap your property names in quotes, you can use bizarre property names like:

var myObj = {
  '^': 'foo'
};
console.log(myObj['^']);

but, I generally stick to more standard names that I can access with dot notation.



来源:https://stackoverflow.com/questions/20336085/how-to-access-object-property-beginning-with-a-number-syntaxerror-unexpected-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!