How do you easily create empty matrices javascript?

前端 未结 17 1422
[愿得一人]
[愿得一人] 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: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); });
    

提交回复
热议问题