How can I create a two dimensional array in JavaScript?

后端 未结 30 4294
天涯浪人
天涯浪人 2020-11-21 05:25

I have been reading online and some places say it isn\'t possible, some say it is and then give an example and others refute the example, etc.

  1. How do I dec

30条回答
  •  孤独总比滥情好
    2020-11-21 05:48

    Similar to activa's answer, here's a function to create an n-dimensional array:

    function createArray(length) {
        var arr = new Array(length || 0),
            i = length;
    
        if (arguments.length > 1) {
            var args = Array.prototype.slice.call(arguments, 1);
            while(i--) arr[length-1 - i] = createArray.apply(this, args);
        }
    
        return arr;
    }
    
    createArray();     // [] or new Array()
    
    createArray(2);    // new Array(2)
    
    createArray(3, 2); // [new Array(2),
                       //  new Array(2),
                       //  new Array(2)]
    

提交回复
热议问题