簡體   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