简体   繁体   中英

Adding dynamic variables in object keys

Is something like this allowed in Javascript:

var object = {
    'key1' + var1 : 'value',
    'key2' + var1 : 'value'
};

I'd liked to concat the var1 variable with the key but I'm getting a syntax error. Here's the full error:

Uncaught SyntaxError: Unexpected token + 

No, obviously( You are getting an error ),

But you can do this:

var obj = {};
obj["key1" + var1] = 'value';

It's using bracket notation to set the dynamic so called key

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