Dash on the end of javascript object property [duplicate]

只愿长相守 提交于 2019-12-13 22:53:58

问题


can i use dash on the end of javascript object property name like this. I could not find in any documentation that this is not valid but i got some strange results when trying to access value myProp- in this case.

var myObject = {"myProp-":"myValue"};

i can only access to this value like this myObject["myProp-"] and i would like to access like

myObject.myProp-

but i got " SyntaxError: Unexpected token } "


回答1:


You'll have to use bracket notation instead of dot notation:

myObject["myProp-"]



回答2:


var myObject = {"myProp-":"myValue", "foo": "bar" };

myObject.foo;
myObject["foo"]; // these are equivalent

myObject.myProp-; // syntax error
myObject["myProp-"]; // this is fine

var key = "myProp-";
myObject[key]; // this works as well (dynamic index)
myObject.key; // undefined

Bracket notation are dot notation are equivalent.



来源:https://stackoverflow.com/questions/15815219/dash-on-the-end-of-javascript-object-property

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