简体   繁体   English

JavaScript将值添加到多维数组

[英]JavaScript Add Values to Multidimensional Array

Hi I am trying to add some values to a multidimensional array using a for loop. 嗨,我正在尝试使用for循环向多维数组添加一些值。 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是一个多维数组,其中包含:

top10数组

It can contain more data that's why I need a for loop. 它可能包含更多数据,这就是为什么我需要for循环的原因。 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". 我正在尝试创建2个多维数组“ test1”和“ test2”,其中一个包含“欣克利火车站”和“ 4754”,另一个包含“欣克利火车站”和“ 2274”。

I can have multiple venues not just "Hinckley Train Station" "4754" "2274" I could also have "London City" "5000" "1000". 我可以有多个场馆,而不仅仅是“欣克利火车站”,“ 4754”,“ 2274”。我还可以拥有“伦敦市”,“ 5000”,“ 1000”。 This is why it is a for loop. 这就是为什么它是for循环的原因。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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