Dash on the end of javascript object property [dup

2019-09-19 18:56发布

This question already has an answer here:

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 } "

2条回答
地球回转人心会变
2楼-- · 2019-09-19 19:07
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.

查看更多
成全新的幸福
3楼-- · 2019-09-19 19:11

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

myObject["myProp-"]
查看更多
登录 后发表回答