How do you easily create empty matrices javascript?

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

提交回复
热议问题