I'm trying to initialise some data values dynamically inside a javascript object, but when I create a concatenated string to pass along, the actual key stored is the variable name, instead of the value inside it.
Example:
projects.init = function(){
for (var i = this.numBoxes - 1; i >= 0; i--){
var toInject = "item"+i;
this.datas[i] = {toInject:"testdata"};
};
}
Then after calling init, the values inside projects.datas look like.. toInject "testdata", instead of being "item1"..."item2".... what am I doing wrong..?
You should build your object in two steps, and use the bracket notation property accessor :
projects.init = function(){
for (var i = this.numBoxes - 1; i >= 0; i--){
var toInject = "item"+i,
obj = {};
obj[toInject] = "testdata";
this.datas[i] = obj;
};
}
The labels on object literals cannot be expressions.
As you can see, first you declare an empty object literal :
var obj = {};
And then you set the property:
obj[toInject] = "testdata";
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.