[英]Assigning variables to objects in JavaScript
I am using the following method to basically create a JSON string. 我正在使用以下方法基本上创建一个JSON字符串。
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. 但是,.a和.c并不能满足我的需要,我需要将它们替换为字符串。 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: 请注意,在JavaScript中,以下符号是等效的:
obj.key
obj["key"]
Use the map accessor: 使用地图访问器:
var name = 'wibble'
saveData[name] = 2
You can access Javascript objects using a dictionary notation: 您可以使用字典符号访问Javascript对象:
var name = 'wibble';
saveData[name] = 2;
saveData.wibble is now 2. saveData.wibble现在为2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.