简体   繁体   中英

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];

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

This for any items on MasterArray.

My first idea is to create a new array one for each MasterArray items, something like this

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] = [];
}

EDIT:

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:

myArray[0].push(5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM