How do you easily create empty matrices javascript?

前端 未结 17 1298
[愿得一人]
[愿得一人] 2020-12-04 16:29

In python, you can do this:

[([None] * 9) for x in range(9)]

and you\'ll get this:

[[None, None, None, None, None, None, No         


        
相关标签:
17条回答
  • 2020-12-04 17:11

    Array.fill

    Consider using fill:

    Array(9).fill().map(()=>Array(9).fill())
    

    The idea here is that fill() will fill out the items with undefined, which is enough to get map to work on them.

    You could also fill directly:

    Array(9).fill(Array(9))
    

    Alternatives to Array(9).fill() include

    Array(...Array(9))
    [].push(...Array(9))
    [].concat(Array(9))
    Array.from(Array(9))
    

    We can rewrite the solution a bit more semantically as:

    function array9() { return Array(9).fill(); }
    array9().map(array9)
    

    or

    function array(n) { return Array(n).fill(); }
    array(9).map(() => array(9))
    

    Array.from provides us with an optional second mapping argument, so we have the alternative of writing

    Array.from(Array(9), () => Array.from(Array(9));
    

    or, if you prefer

    function array9(map) { return Array.from(Array(9), map); }
    array9(array9);
    

    For verbose description and examples, see Mozilla's Docs on Array.prototype.fill() here.
    and for Array.from(), here.

    Note that neither Array.prototype.fill() nor Array.from() has support in Internet Explorer. A polyfill for IE is available at the above MDN links.

    Partitioning

    partition(Array(81), 9)
    

    if you have a partition utility handy. Here's a quick recursive one:

    function partition(a, n) {
      return a.length ? [a.splice(0, n)].concat(partition(a, n)) : [];
    }  
    

    Looping

    We can loop a bit more efficiently with

    var a = [], b;
    while (a.push(b = []) < 9) while (b.push(null) < 9);
    

    Taking advantage of the fact that push returns the new array length.

    0 讨论(0)
  • 2020-12-04 17:11

    This is an exact fix to your problem, but I would advise against initializing the matrix with a default value that represents '0' or 'undefined', as Arrays in javascript are just regular objects, so you wind up wasting effort. If you want to default the cells to some meaningful value, then this snippet will work well, but if you want an uninitialized matrix, don't use this version:

    /**
    * Generates a matrix (ie: 2-D Array) with: 
    * 'm' columns, 
    * 'n' rows, 
    * every cell defaulting to 'd';
    */
    function Matrix(m, n, d){
        var mat = Array.apply(null, new Array(m)).map(
            Array.prototype.valueOf,
            Array.apply(null, new Array(n)).map(
                function() {
                   return d;
                }
            )
        );
        return mat;
    }
    

    Usage:

    < Matrix(3,2,'dobon');
    > Array [ Array['dobon', 'dobon'], Array['dobon', 'dobon'], Array['dobon', 'dobon'] ]
    

    If you would rather just create an uninitialized 2-D Array, then this will be more efficient than unnecessarily initializing every entry:

    /**
    * Generates a matrix (ie: 2-D Array) with: 
    * 'm' columns, 
    * 'n' rows, 
    * every cell remains 'undefined';
    */
    function Matrix(m, n){
        var mat = Array.apply(null, new Array(m)).map(
            Array.prototype.valueOf,
            new Array(n)
        );
        return mat;
    }
    

    Usage:

    < Matrix(3,2);
    > Array [ Array[2], Array[2], Array[2] ]
    
    0 讨论(0)
  • 2020-12-04 17:11

    With ES6 spread operator: Array(9).fill([...Array(9)])

    0 讨论(0)
  • 2020-12-04 17:13

    If you really like one-liners and there is a use for underscore.js in your project (which is a great library) you can do write-only things like:

    _.range(9).map(function(n) {
          return _.range(9).map(function(n) {
                return null;
          });
    });
    

    But I would go with standard for-cycle version mentioned above.

    0 讨论(0)
  • 2020-12-04 17:15

    JavaScript doesn’t have a built-in 2D array concept, but you can certainly create an array of arrays.

    function createMatrix(row, column, isEmpty) {
            let matrix = []
            let array = []
            let rowColumn = row * column
            for (let i = 1; i <= rowColumn; i++) {
                isEmpty ?  array.push([]) :  array.push(i)
    
                if (i % column === 0) {
                    matrix.push(array)
                    array = []
                }
            }
            return matrix
        }
    
    createMatrix(5, 3, true)
    

    or

    function createMatrix(row, column, from) {
    
            let [matrix, array] = [[], []],
                total = row * column
    
            for (let element = from || 1; element <= total; element++) {
                array.push(element)
                if (element % column === 0) {
                    matrix.push(array)
                    array = []
                }
            }
    
            return matrix
        }
    
    createMatrix(5, 6, 1)
    
    0 讨论(0)
提交回复
热议问题