最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Value is the variable name instead of the contents of the variable - Stack Overflow

programmeradmin6浏览0评论

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..?

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..?

Share Improve this question asked Nov 21, 2009 at 18:12 danpdanp 15.3k7 gold badges46 silver badges48 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

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";
发布评论

评论列表(0)

  1. 暂无评论