admin管理员组

文章数量:1317910

So I have this plain object

var data = {};

And i want to fill it with key-value pairs in a for loop like this

for(var i=0; i<n; i++){
    $.extend(
        data,
        {
            'a'+toString(i): someFunction(i),
            'b'+toString(i): someFunction(i)
        };
    );
};

but seems like it's impossible to concatenate strings when defining the key. Is there any neat way to do what I need, because I feel like my approach is lame from the very begining.

Thanks.

So I have this plain object

var data = {};

And i want to fill it with key-value pairs in a for loop like this

for(var i=0; i<n; i++){
    $.extend(
        data,
        {
            'a'+toString(i): someFunction(i),
            'b'+toString(i): someFunction(i)
        };
    );
};

but seems like it's impossible to concatenate strings when defining the key. Is there any neat way to do what I need, because I feel like my approach is lame from the very begining.

Thanks.

Share Improve this question edited Dec 5, 2014 at 11:00 Mark Walters 12.4k6 gold badges35 silver badges48 bronze badges asked Feb 26, 2014 at 16:42 yur15tyur15t 3171 gold badge5 silver badges15 bronze badges 1
  • 'a'+toString(i) doesn't do what you think it does. – georg Commented Feb 26, 2014 at 16:59
Add a ment  | 

2 Answers 2

Reset to default 7

Use this syntax

for ( var i = 0; i < n; i++ ) {
    data['a'+toString(i)] = someFunction(i);
}

To use a non-literal key with an object you need to use the square bracket notation. This allows you to create dynamic keys.

Have a look here for more info on square bracket notation

You need to use bracket notation as the member operator since the keys are dynamic

for (var i = 0; i < n; i++) {
    data['a' + toString(i)] = someFunction(i);
    data['b' + toString(i)] = someFunction(i);
}

本文标签: javascriptConcatenate strings in key of plain objectStack Overflow