简体   繁体   中英

Assigning variables to objects in JavaScript

I am using the following method to basically create a JSON string.

var saveData = {};
saveData.a = 2;
saveData.c = 1;

However the .a and .c don't cut it for what I need to do, I need to replace these with strings. So something like..

var name = 'wibble';
saveData.name = 2;

This would get accessed with

saveData.wibble

Does anyone know how this could be achieved?

var name = "wibble";
saveData[name] = 2;

alert(saveData.wibble);

Note that, in JavaScript, the following notations are equivalent:

obj.key
obj["key"]

Use the map accessor:

var name = 'wibble'
saveData[name] = 2

You can access Javascript objects using a dictionary notation:

var name = 'wibble';
saveData[name] = 2;

saveData.wibble is now 2.

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