How can I create a two dimensional array in JavaScript?

后端 未结 30 4402
天涯浪人
天涯浪人 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条回答
  •  猫巷女王i
    2020-11-21 05:33

    Use Array Comprehensions

    In JavaScript 1.7 and higher you can use array comprehensions to create two dimensional arrays. You can also filter and/or manipulate the entries while filling the array and don't have to use loops.

    var rows = [1, 2, 3];
    var cols = ["a", "b", "c", "d"];
    
    var grid = [ for (r of rows) [ for (c of cols) r+c ] ];
    
    /* 
             grid = [
                ["1a","1b","1c","1d"],
                ["2a","2b","2c","2d"],
                ["3a","3b","3c","3d"]
             ]
    */
    

    You can create any n x m array you want and fill it with a default value by calling

    var default = 0;  // your 2d array will be filled with this value
    var n_dim = 2;
    var m_dim = 7; 
    
    var arr = [ for (n of Array(n_dim)) [ for (m of Array(m_dim) default ]] 
    /* 
             arr = [
                [0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0],
             ]
    */
    

    More examples and documentation can be found here.

    Please note that this is not a standard feature yet.

提交回复
热议问题