How can I create a two dimensional array in JavaScript?

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

    The reason some say that it isn't possible is because a two dimensional array is really just an array of arrays. The other comments here provide perfectly valid methods of creating two dimensional arrays in JavaScript, but the purest point of view would be that you have a one dimensional array of objects, each of those objects would be a one dimensional array consisting of two elements.

    So, that's the cause of the conflicting view points.

    0 讨论(0)
  • 2020-11-21 05:51

    Two-liner:

    var a = []; 
    while(a.push([]) < 10);
    

    It will generate an array a of the length 10, filled with arrays. (Push adds an element to an array and returns the new length)

    0 讨论(0)
  • 2020-11-21 05:51

    Javascript does not support two dimensional arrays, instead we store an array inside another array and fetch the data from that array depending on what position of that array you want to access. Remember array numeration starts at ZERO.

    Code Example:

    /* Two dimensional array that's 5 x 5 
    
           C0 C1 C2 C3 C4 
        R0[1][1][1][1][1] 
        R1[1][1][1][1][1] 
        R2[1][1][1][1][1] 
        R3[1][1][1][1][1] 
        R4[1][1][1][1][1] 
    */
    
    var row0 = [1,1,1,1,1],
        row1 = [1,1,1,1,1],
        row2 = [1,1,1,1,1],
        row3 = [1,1,1,1,1],
        row4 = [1,1,1,1,1];
    
    var table = [row0,row1,row2,row3,row4];
    console.log(table[0][0]); // Get the first item in the array
    
    0 讨论(0)
  • 2020-11-21 05:51
    Array(m).fill(v).map(() => Array(n).fill(v))
    

    You can create a 2 Dimensional array m x n with initial value m and n can be any numbers v can be any value string, number, undefined.

    One approach can be var a = [m][n]

    0 讨论(0)
  • 2020-11-21 05:52

    Two dimensional arrays are created the same way single dimensional arrays are. And you access them like array[0][1].

    var arr = [1, 2, [3, 4], 5];
    
    alert (arr[2][1]); //alerts "4"
    
    0 讨论(0)
  • 2020-11-21 05:54

    My approach is very similar to @Bineesh answer but with a more general approach.

    You can declare the double array as follows:

    var myDoubleArray = [[]];
    

    And the storing and accessing the contents in the following manner:

    var testArray1 = [9,8]
    var testArray2 = [3,5,7,9,10]
    var testArray3 = {"test":123}
    var index = 0;
    
    myDoubleArray[index++] = testArray1;
    myDoubleArray[index++] = testArray2;
    myDoubleArray[index++] = testArray3;
    
    console.log(myDoubleArray[0],myDoubleArray[1][3], myDoubleArray[2]['test'],) 
    

    This will print the expected output

    [ 9, 8 ] 9 123
    
    0 讨论(0)
提交回复
热议问题