简体   繁体   中英

How can I statically declare a Javascript object instance (a.k.a “associative array”) whose property names (a.k.a keys) contain dashes?

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:

  • as an identifier name ( foo )
  • as a number literal ( 42 )
  • as a string literal ( 'foo bar' )
  • as a computed property ( [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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM