How do you easily create empty matrices javascript?

前端 未结 17 1293
[愿得一人]
[愿得一人] 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:01

    Well, you can create an empty 1-D array using the explicit Array constructor:

    a = new Array(9)

    To create an array of arrays, I think that you'll have to write a nested loop as Marc described.

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

    I'll give it my shot as well

    var c = Array;
    
    for( var i = 0, a = c(9); i < 9; a[i] = c(9), i++ );
    
    console.log( a.join(",") );
    //",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"
    

    Readable and maintainable !

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

    better. that exactly will work.

    let mx = Matrix(9, 9);
    
    function Matrix(w, h){
        let mx = Array(w);
        for(let i of mx.keys())
            mx[i] = Array(h);
        return mx;
    }
    


    what was shown

    Array(9).fill(Array(9)); // Not correctly working
    

    It does not work, because all cells are fill with one array

    0 讨论(0)
  • 2020-12-04 17:09
    var matrix = [];
    for(var i=0; i<9; i++) {
        matrix[i] = new Array(9);
    }
    

    ... or:

    var matrix = [];
    for(var i=0; i<9; i++) {
        matrix[i] = [];
        for(var j=0; j<9; j++) {
            matrix[i][j] = undefined;
        }
    }
    
    0 讨论(0)
  • 2020-12-04 17:09

    You can add functionality to an Array by extending its prototype object.

    Array.prototype.nullify = function( n ) {
        n = n >>> 0;
        for( var i = 0; i < n; ++i ) {
            this[ i ] = null;
        }
        return this;
    };
    

    Then:

    var arr = [].nullify(9);
    

    or:

    var arr = [].nullify(9).map(function() { return [].nullify(9); });
    
    0 讨论(0)
  • 2020-12-04 17:10

    Here's one, no looping:

    (Math.pow(10, 20)+'').replace((/0/g),'1').split('').map(parseFloat);
    

    Fill the '20' for length, use the (optional) regexp for handy transforms and map to ensure datatype. I added a function to the Array prototype to easily pull the parameters of 'map' into your functions.. bit risky, some people strongly oppose touching native prototypes, but it does come in handy..

        Array.prototype.$args = function(idx) {
            idx || (idx = 0);
            return function() {
                return arguments.length > idx ? arguments[idx] : null;
            };
        };
    
    // Keys
    (Math.pow(10, 20)+'').replace((/0/g),'1').split('').map(this.$args(1));
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    
    // Matrix
    (Math.pow(10, 9)+'').replace((/0/g),'1').split('').map(this.$args(1)).map(this.$args(2))
    
    0 讨论(0)
提交回复
热议问题