如何创建具有动态密钥名的javascript关联数组{}?

时间:2022-08-26 14:16:05

Basically I have a loop incrementing i, and I want to do this:

基本上我有一个循环递增I,我想这样做

var fish = { 'fishInfo[' + i + '][0]': 6 };

however it does not work.

然而,它不起作用。

Any ideas how to do this? I want the result to be

有什么办法吗?我希望结果是。

fish is { 'fishInfo[0][0]': 6 };
fish is { 'fishInfo[1][0]': 6 };
fish is { 'fishInfo[2][0]': 6 };

etc.

等。

I am using $.merge to combine them if you think why on earth is he doing that :)

我用美元。如果你认为他为什么要这样做的话,那就合并起来吧

4 个解决方案

#1


9  

Declare an empty object, then you can use array syntax to assign properties to it dynamically.

声明一个空对象,然后可以使用数组语法动态地分配属性。

var fish = {};

fish[<propertyName>] = <value>;

#2


5  

Do this:

这样做:

var fish = {};
fish['fishInfo[' + i + '][0]'] =  6;

It works, because you can read & write to objects using square brackets notation like this:

它是有效的,因为你可以用方括号这样的符号来读写对象:

my_object[key] = value;

and this:

这:

alert(my_object[key]);

#3


2  

For any dynamic stuff with object keys, you need the bracket notation.

对于任何具有对象键的动态对象,您需要使用括号表示法。

var fish = { };

fish[ 'fishInfo[' + i + '][0]' ] = 6;

#4


0  

Multidimensional Arrays in javascript are created by saving an array inside an array.

javascript中的多维数组是通过保存数组中的数组创建的。

Try:

试一试:

var multiDimArray = [];
for(var x=0; x<10; x++){
    multiDimArray[x]=[];
    multiDimArray[x][0]=6;
}

Fiddle Exampe: http://jsfiddle.net/CyK6E/

小提琴Exampe:http://jsfiddle.net/CyK6E/

#1


9  

Declare an empty object, then you can use array syntax to assign properties to it dynamically.

声明一个空对象,然后可以使用数组语法动态地分配属性。

var fish = {};

fish[<propertyName>] = <value>;

#2


5  

Do this:

这样做:

var fish = {};
fish['fishInfo[' + i + '][0]'] =  6;

It works, because you can read & write to objects using square brackets notation like this:

它是有效的,因为你可以用方括号这样的符号来读写对象:

my_object[key] = value;

and this:

这:

alert(my_object[key]);

#3


2  

For any dynamic stuff with object keys, you need the bracket notation.

对于任何具有对象键的动态对象,您需要使用括号表示法。

var fish = { };

fish[ 'fishInfo[' + i + '][0]' ] = 6;

#4


0  

Multidimensional Arrays in javascript are created by saving an array inside an array.

javascript中的多维数组是通过保存数组中的数组创建的。

Try:

试一试:

var multiDimArray = [];
for(var x=0; x<10; x++){
    multiDimArray[x]=[];
    multiDimArray[x][0]=6;
}

Fiddle Exampe: http://jsfiddle.net/CyK6E/

小提琴Exampe:http://jsfiddle.net/CyK6E/