簡體   English   中英

如何將一個陣列推入另一個陣列?

[英]How can i push a array in another array?

我有64個位置的主數組,每個位置我都需要另一個數組。 例如: someArray[index] = [someObject]

我如何創建這些數組? 以及如何獲取someObject.name , someObject.lastName

這是代碼:

$scope.filaCores = []; 
$scope.object = {} 
$scope.object.name = "name"; 
$scope.object.secondname= "secondname"; 
for(var i = 0; i <10; i++) { 
   $scope.filaCores[i] = [$scope.object.name, $scope.object.secondname]; 
} 

在這里您可以前往: https : //jsfiddle.net/jsg81gg8/1/

根據您的描述,我認為不需要數組。 但是既然是您要的,那就去吧。 您沒有為子數組指定多少個數組元素,所以我將顯示一個包含三個的示例。 如果僅需要64個結構,則不需要內部數組。

window.getRandomInt = function() {
    return Math.floor(Math.random() * (10000 - 1 + 1)) + 1;
}

mainArray = [];  /* you said you wanted 64 of these */
subArray = [];  /* you didn't specify how many of these, the example below will assume 3 per each mainarray */

for (i = 0; i < 64; i++) {
    for (j = 0; j < 3; j++) {
        /* I'm using getRandomInt() just so you can see all the names are different */
        subArray[j] = {name:"John"+getRandomInt(), lastname:"Doe"+getRandomInt()};
        }
    mainArray[i] = subArray;
}

/* Press F12 and go to the console tab, run this script, and you will see the output of the entire array */
console.log(mainArray);

/* You can access a specific element like this... */
alert('Alerting mainArray[23][2].lastname: '+mainArray[23][2].lastname);

如果確實不需要子數組,而只需要64個結構,則可以簡化為以下形式: https : //jsfiddle.net/Ldafbwbk/1/

更新:這是第三個示例,它與您更新的問題更加相似: https : //jsfiddle.net/7st8fnw5/3/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM