Javascript 生成空二维数组的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6495187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:02:31  来源:igfitidea点击:

best way to generate empty 2D array

javascriptarrays

提问by vsync

is there a shorter, better way to generate 'n' length 2D array?

有没有更短、更好的方法来生成“n”长度的二维数组?

var a = (function(){ var i=9, arr=[]; while(i--) arr.push([]); return arr })();

a // [ [],[],[],[],[],[],[],[],[] ]

** old-school short-way**:

** 老式短途**:

var a = (function(a){ while(a.push([]) < 9); return a})([]);

UPDATE - Using ES2015

更新 - 使用 ES2015

Array(5).fill().map(a=>[]); // will create 5 Arrays in an Array
// or
Array.from({length:5}, a=>[])

Emptying 2D array(saves memory rather)

清空二维数组(更节省内存)

function make2dArray(len){
    var a = [];
    while(a.push([]) < len); 
    return a;
}

function empty2dArray(arr){
    for( var i = arr.length; i--; )
      arr[i].length = 0;
}

// lets make a 2D array of 3 items
var a = make2dArray(3);

// lets populate it a bit
a[2].push('demo');
console.log(a); // [[],[],["demo"]]

// clear the array
empty2dArray(a);
console.log(a); // [[],[],[]]

回答by Felix Kling

Another way:

其它的办法:

for(var a = [];a.length < 10; a.push([])); // semicolon is mandatory here

Yet another way:

还有一种方式:

var a = []; while(a.push([]) < 10);

This works because .push()[docs](specification) returns the new length of the array.

这是有效的,因为.push()[docs]规范)返回数组的新长度。



That said, this is the wrong way of "reducing code". Create a dedicated function with a meaningful name and use this one. Your code will be much more understandable:

也就是说,这是“减少代码”的错误方式。创建一个具有有意义名称的专用函数并使用这个函数。你的代码会更容易理解:

function get2DArray(size) {
    size = size > 0 ? size : 0;
    var arr = [];

    while(size--) {
        arr.push([]);
    }

    return arr;
}

var a = get2DArray(9);

Code is read much more often than written.

代码的阅读频率远高于编写代码。

回答by Xlee

Just discovered another ES6way with one line expression:

刚刚用一行表达式发现了另一种ES6方式:

Array.from({length: N}, () => [])

Array.from(arrayLike[, mapFn[, thisArg]])

Array.from(arrayLike[, mapFn[, thisArg]])

More detail about its implementation/polyfill ? MDN Array.from()

有关其实现/polyfill 的更多详细信息?MDN Array.from()

Yet another neat solution with help of array spread syntax:

另一个巧妙的解决方案,帮助array spread syntax

[...Array(N)].map(() => [])

回答by sugavaneshb

Array(cardinality).fill(0).map(function(item) {return [];});

where cardinality is the number of items you are looking at. In this case it would be 9. This was suggested by one of my colleagues actually. This is neat, I think :) This is valid from ECMA V6. Documentation: Array::fill

其中基数是您正在查看的项目数。在这种情况下,它将是 9。这实际上是我的一位同事建议的。这很好,我认为 :) 这从 ECMA V6 开始有效。文档:数组::填充

回答by user1542

for(var i=9,a=[];i>=0;i--){ a.push([]) }

回答by user1542

In ES6:

在 ES6 中:

(m, n, initialElementValue) => Array(m).fill(Array(n).fill(initialElementValue))

回答by Sergey Semushin

var x = 3, y = 5, arr = Array(y).fill();
arr = arr.map(function(){return Array(x).fill(' ')});
console.log(arr);

回答by Zum Dummi

best way to generate 2D array in js by ES6 by Array.from

通过 ES6 在 js 中生成二维数组的最佳方法 Array.from

function twodimension(input) {
  let index = 0,
    sqrt = Math.sqrt(input.length);

  return Array.from({
    length: sqrt
  }, (nothing, i) => Array.from({
    length: sqrt
  }, (nothingTwo, j) => input[index++]))
}

console.log(twodimension('abcdefghijklmnopqrstupwxy'))
console.log(twodimension([1,2,3,4,5,6,7,8,9]))

function input(length, fill) {
  let getNums = length * length;
  let fillNums = 1
  if (fill == 'minus') {
    return Array.from({
      length: length
    }, (nothing, i) => Array.from({
      length: length
    }, (nothingTwo, j) => getNums--))
  } else if (fill == 'plus') {
    return Array.from({
      length: length
    }, (nothing, i) => Array.from({
      length: length
    }, (nothingTwo, j) => fillNums++))
  }
  
  // you can dping snake ladders also with Array.from

  if (fill === 'snakes') {
    return Array.from({
        length: length
      }, (_, one) =>
      Array.from({
        length: length
      }, (_, two) => getNums--)
    ).map((el, i) =>
      i % 2 == 1 && length % 2 == 0 ? el.reverse() :
      i % 2 == 0 && length % 2 == 1 ? el.reverse() : el
    );
  }


}

console.log(input(8, 'minus'))
console.log(input(10, 'plus'))

console.log(input(5, 'snakes'))

you do anything with Array.from, it is easy to use and fast, this is the new method in ES6 syntax

你可以用Array.from做任何事情,它易于使用且速度快,这是ES6语法中的新方法

回答by Nathan Romano

var a = []; for(var i=0;i<10;i++) { a[i] = []; }

回答by malko

shorter way can be :

更短的方法可以是:

for(var i=9,a=[];i>=0;i--){ a.push([]) }

回答by Naftali aka Neal

var a = [];
var max_length = 10;
for(var i = 0; i < max_length; ++i){ 
    a[i] = []; 
}