How can I create a two dimensional array in JavaScript?

后端 未结 30 4274
天涯浪人
天涯浪人 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:41

    Here's a quick way I've found to make a two dimensional array.

    function createArray(x, y) {
        return Array.apply(null, Array(x)).map(e => Array(y));
    }
    

    You can easily turn this function into an ES5 function as well.

    function createArray(x, y) {
        return Array.apply(null, Array(x)).map(function(e) {
            return Array(y);
        });
    }
    

    Why this works: the new Array(n) constructor creates an object with a prototype of Array.prototype and then assigns the object's length, resulting in an unpopulated array. Due to its lack of actual members we can't run the Array.prototype.map function on it.

    However, when you provide more than one argument to the constructor, such as when you do Array(1, 2, 3, 4), the constructor will use the arguments object to instantiate and populate an Array object correctly.

    For this reason, we can use Array.apply(null, Array(x)), because the apply function will spread the arguments into the constructor. For clarification, doing Array.apply(null, Array(3)) is equivalent to doing Array(null, null, null).

    Now that we've created an actual populated array, all we need to do is call map and create the second layer (y).

提交回复
热议问题