动态添加一个多维数组在javascript或jquery

时间:2021-12-10 21:36:02

The problem is I need to add a multi dimension array dynamically, please look at the following example:

问题是我需要动态添加一个多维数组,请看下面的例子:

var list = [];
var listname;
var height;
var width;

list.push(listname);
list[listname] = height;
list[listname] = width;

the code above is not what I expected , which should be [listname => [[0]=>height,[1]=>width]], what can I do if I do not want to create an array for listname, can I dynamic add a mulit dimension array ? thanks.

上面的代码不是我想要的,应该是[listname => [[0]=>height,[1]=>width]],如果我不想为listname创建一个数组,我可以动态添加一个mulit维度数组吗?谢谢。

1 个解决方案

#1


4  

Don't confuse Arrays with Maps. They are different fundamental data-types1

不要混淆数组和映射。它们是不同的基本数据类型1

var myLists = {};       // name => array
var listname = "stuff"; // why not?
var height = 1;
var width = 2;

// there is no Object.push, but we can assign a property by name
myLists[listName] = [height];
// then we can Array.push into the array we just assigned
myLists[listName].push(width);

Then, myLists:

然后,mylist:

{
   stuff: [1, 2]
}

1JavaScript mostly maintains this distinction - if one doesn't add random properties to Arrays or otherwise fake an Object to behave like an array.

1JavaScript基本上保持了这种区别——如果不向数组添加随机属性,或者假装对象像数组一样运行的话。

#1


4  

Don't confuse Arrays with Maps. They are different fundamental data-types1

不要混淆数组和映射。它们是不同的基本数据类型1

var myLists = {};       // name => array
var listname = "stuff"; // why not?
var height = 1;
var width = 2;

// there is no Object.push, but we can assign a property by name
myLists[listName] = [height];
// then we can Array.push into the array we just assigned
myLists[listName].push(width);

Then, myLists:

然后,mylist:

{
   stuff: [1, 2]
}

1JavaScript mostly maintains this distinction - if one doesn't add random properties to Arrays or otherwise fake an Object to behave like an array.

1JavaScript基本上保持了这种区别——如果不向数组添加随机属性,或者假装对象像数组一样运行的话。