best way to generate empty 2D array

前端 未结 10 1109
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 07:03

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

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

a // [ [],         


        
相关标签:
10条回答
  • 2020-12-01 07:21

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

    0 讨论(0)
  • 2020-12-01 07:24

    best way to generate 2D array in js by ES6 by 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

    0 讨论(0)
  • 2020-12-01 07:31

    In ES6:

    (m, n, initialElementValue) => Array(m).fill(Array(n).fill(initialElementValue))
    
    0 讨论(0)
  • 2020-12-01 07:33

    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.


    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.

    0 讨论(0)
提交回复
热议问题