简体   繁体   中英

create two dimension array and push values in javascript

Here i am creating two dimensional array and push values into it. In this code i create empty array using for loop and again i am using forloop to push the values into an array.My question I need to create an array and push the values in an array with one time for loop.

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

answer either in javascript or jquery

try this ,for a O(n) loop:

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

if you ok with an O(n^2) nested loop:

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

Try with:

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

My question I need to create an array and push the values in an array with one time for loop

If expected result is console.log(JSON.stringify(arr));//[[0,1,2],[0,1,2],[0,1,2],[0,1,2]] , could push initial array item to same array ?

If arr.length is 0 push tot , tot + 1 , tot + 2 to arr , else push arr[0] to 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)); 

Just use function method Function.prototype.apply() with an object which specifies the length and array method Array.prototype.map() for filling with another array and the values.

 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>'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM