简体   繁体   中英

JavaScript Add Values to Multidimensional Array

Hi I am trying to add some values to a multidimensional array using a for loop. This is what I have created so far:

var test1 = [];
var test2 = [];
for (var i = 0; i < top10.length; i++)
{
    test1[i] = i;
    test1[i][0] = top10[i][0];
    test1[i][1] = top10[i][1];
}

This is just returning an empty array. top10 is a multidimensional array which contains:

top10数组

It can contain more data that's why I need a for loop. I am trying to create 2 multidimensional arrays "test1" and "test2" one will contain "Hinckley Train Station" and "4754" the other will contain "Hinckley Train Station" and "2274".

I can have multiple venues not just "Hinckley Train Station" "4754" "2274" I could also have "London City" "5000" "1000". This is why it is a for loop.

You could push a new array to the wanted parts

 var top10 = [ ["Hinckley Train Station", "4754", "2274"], ["London City", "5000", "1000"] ], test1 = [], test2 = [], i; for (i = 0; i < top10.length; i++) { test1.push([top10[i][0], top10[i][1]]); test2.push([top10[i][0], top10[i][2]]); } console.log(test1); console.log(test2); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

In this line

test1[i] = i;

You are assigning an integer to be the first element of the outer array. You don't have a 2d array, you have an array of integers

In the following lines:

test1[i][0] = top10[i][0];
test1[i][1] = top10[i][1];

You are assigning properties to an integer, which means they are being boxed but the boxed value is thrown away.

It's hard to tell what you are trying to do, but the following is probably closer. You need to create a new inner array each time through the loop.

for (var i = 0; i < top10.length; i++)
{
    test1[i] = [];
    test1[i][0] = top10[i][0];
    test1[i][1] = top10[i][1];
    // Maybe do something similar with test2
}

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