[英]Javascript array with index and multiple items on it
I've to do a strange thing and I don't know if is possible.我必须做一件奇怪的事情,我不知道是否可能。
Let assume I've one aray假设我有一个阵列
MasterArray = [1,2,3,4]; MasterArray = [1,2,3,4];
Now for each MasterArray item I need to have multiple insertion, for example under the item 1 I've to push N value, for example the MasterArray[0] must have this correlations 5,8,3,9 ...现在对于每个 MasterArray 项目,我需要多次插入,例如在项目 1 下我必须推送 N 值,例如 MasterArray[0] 必须具有此相关性 5,8,3,9 ...
This for any items on MasterArray.这适用于 MasterArray 上的任何项目。
My first idea is to create a new array one for each MasterArray items, something like this我的第一个想法是为每个 MasterArray 项目创建一个新数组,就像这样
var newobject = X;
for (i = 0; i < MasterArray.length; i++) {
Arr[i] = push the newobject ;
}
But I don't think that is a good way!但我认为这不是一个好方法!
The purpose it to have a kind of correlated array.目的是要有一种相关的数组。
MasterArray[0] is correlated to another array [5,8,3,9, ...]
MasterArray[1] is correlated to another array [5,6,7,1, ...]
MasterArray[2] is correlated to another array [7,45,23,2, ...]
And so on等等
I hope to have explained myself我希望已经解释了自己
Just create a 2D array in this way:只需以这种方式创建一个二维数组:
var myArray = new Array(5); // For example 5;
for (var i = 0; i < myArray.length; i++) {
myArray[i] = new Array(10);
}
Or, if you don't need to specify any size:或者,如果您不需要指定任何尺寸:
var myArray = new Array(5); // For example 5;
for (var i = 0; i < myArray.length; i++) {
myArray[i] = [];
}
For manipulate you just need to use innested loops:对于操作,您只需要使用嵌套循环:
for (var i = 0; i < myArray.length; i++) {
for (var j = 0; i < myArray[i].length; j++) {
myArray[i][j] = x; // where x is some variable
}
For add elements in the back just use .push()
method:要在后面添加元素,只需使用
.push()
方法:
myArray[0].push(5);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.