嗨,我正在尝试使用 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 是一个多维数组,其中包含:
它可以包含更多数据,这就是我需要 for 循环的原因。我正在尝试创建 2 个多维数组“test1”和“test2”,其中一个将包含“欣克利火车站”和“4754”,另一个将包含“欣克利火车站”和“2274”。
我可以有多个 field ,不仅仅是“欣克利火车站”“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; }
关于JavaScript 将值添加到多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45713813/