Value is the variable name instead of the contents of the variable
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";
精彩评论