简体   繁体   English

创建二维数组并在javascript中推送值

[英]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. 在这段代码中,我使用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]]

answer either in javascript or jquery 用javascript或jquery回答

try this ,for a O(n) loop: 试试这个,以获得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]] 

if you ok with an O(n^2) nested loop: 如果您可以接受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]] 

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 ? 如果预期结果是console.log(JSON.stringify(arr));//[[0,1,2],[0,1,2],[0,1,2],[0,1,2]] ,可以将初始数组项推送到同一数组吗?

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

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. 只需对指定长度的对象使用函数方法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