繁体   English   中英

JavaScript将值添加到多维数组

[英]JavaScript Add Values to Multidimensional Array

嗨,我正在尝试使用for循环向多维数组添加一些值。 到目前为止,这是我创建的:

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

这只是返回一个空数组。 top10是一个多维数组,其中包含:

top10数组

它可能包含更多数据,这就是为什么我需要for循环的原因。 我正在尝试创建2个多维数组“ test1”和“ test2”,其中一个包含“欣克利火车站”和“ 4754”,另一个包含“欣克利火车站”和“ 2274”。

我可以有多个场馆,而不仅仅是“欣克利火车站”,“ 4754”,“ 2274”。我还可以拥有“伦敦市”,“ 5000”,“ 1000”。 这就是为什么它是for循环的原因。

您可以将新阵列推入所需零件

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

在这条线

test1[i] = i;

您正在分配一个整数作为外部数组的第一个元素。 您没有二维数组,但有整数数组

在以下几行中:

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

您正在将属性分配给整数,这意味着将其装箱,但将丢弃装箱的值。

很难说出您要做什么,但是以下内容可能更接近。 每次循环时都需要创建一个新的内部数组。

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