I want to statically declare a Javascript object (sometimes referred to as "associative array" when used as such) whose property names ("keys") contain dashes?
Without dashes (works):
myObject = {field_1:"aaa", field_2:"bbb"};
With dashes (results in syntax error):
myObject = {field-1:"aaa", field-2:"bbb"};
(And yes, I'm fully aware that such properties containing dashes can only be referenced by using "bracket notation" rather than "dot notation" , but that's a completely other story, I'm only talking about the case of static declaration of such objects here.)
you have to wrap the property names in quote to read "field-1" as a string.
var myObject = {"field-1":"aaa", "field-2":"bbb"}
console.log(myObject["field-1"], myObject["field-2"])
//computed properties
var name1 = "field-1"
var name2 = "field-2"
var myObject = {
[name1]: "aaa",
[name2]: "bbb"
}
console.log(myObject["field-1"], myObject["field-2"])
Inside an object literal, property names can be defined in four ways:
foo
) 42
) 'foo bar'
) [foo + 'bar']
) field-1
is neither of those. It's not an identifier because the character -
is not valid in identifier names. It's relatively easy to know whether something is a valid identifier name: If it's not a keyword and not a valid variable name, it's not a valid identifier name. That is, since it's invalid to declare the variable
var field-1 = 42;
you cannot use it in a object literal either.
You have to use a string literal instead. A string literal can contain any character sequence:
myObject = {'field-1':"aaa"};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.