簡體   English   中英

創建二維數組並在javascript中推送值

[英]create two dimension array and push values in javascript

在這里,我正在創建二維數組並將值推入其中。 在這段代碼中,我使用for循環創建了一個空數組,再次使用forloop將這些值推入了一個數組。我的問題是我需要創建一個數組並將一次將值推入一個數組中進行一次for循環。

var arr = [];
for (var tot=0;tot<4;tot++) {//creating empty arrays
    arr.push([]);
}
for (var tot=0;tot<4;tot++) {//pushing values into an array
    for (var i=0;i<3;i++) {
        arr[tot].push(i);
    }
}
console.log(JSON.stringify(arr));//[[0,1,2],[0,1,2],[0,1,2],[0,1,2]]

用javascript或jquery回答

試試這個,以獲得O(n)循環:

 var arr = [],dimentions = [3,4]; for (var i = 0; i< dimentions[0] * dimentions[1];i++) { var x = Math.floor(i/dimentions[0]), y = i%dimentions[0]; arr[x] = arr[x] || []; arr[x].push(y); } console.log(JSON.stringify(arr));//[[0,1,2],[0,1,2],[0,1,2],[0,1,2]] 

如果您可以接受O(n ^ 2)嵌套循環:

 var arr = []; for (var i = 0; i < 4; i++) {//pushing values into an array arr[i] = arr[i] || []; for (var j = 0; j < 3;j++) { arr[i].push(j); } } console.log(JSON.stringify(arr));//[[0,1,2],[0,1,2],[0,1,2],[0,1,2]] 

嘗試:

 var arr = []; for (var tot = 0; tot < 4; tot++) { //creating empty arrays arr.push([]); for (var i = 0; i < 3; i++) { arr[tot].push(i); } } console.log(JSON.stringify(arr)); 

我的問題是我需要創建一個數組並一次循環將值推入數組

如果預期結果是console.log(JSON.stringify(arr));//[[0,1,2],[0,1,2],[0,1,2],[0,1,2]] ,可以將初始數組項推送到同一數組嗎?

如果arr.length0arr.length tottot + 1tot + 2推送到arr ,否則將arr[0]推送到arr

 var arr = []; for (var tot = 0; tot < 4; tot++) { if (!arr.length) arr.push([tot, tot + 1, tot + 2]) else arr.push(arr[0]) } console.log(JSON.stringify(arr)); 

只需對指定長度的對象使用函數方法Function.prototype.apply()和用於填充另一個數組和值的數組方法Array.prototype.map()

 var n = 3, array = Array.apply(Array, { length: n }).map(function () { return Array.apply(Array, { length: n }).map(function (_, i) { return i; }); }); document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>'); 

暫無
暫無

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

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