How to create empty 2d array in javascript?

后端 未结 8 1614
执笔经年
执笔经年 2020-12-08 07:07

How do I create an empty 2D array in Javascript (without knowing how many rows or columns there will be in the new array)?

If it\'s a simple array var newArra

8条回答
  •  Happy的楠姐
    2020-12-08 07:24

    Two things:

    1) The array length property improperly reports the array length if called after the var myArray = [[],[]]; statement. Technically, since the empty arrays are defined, they are getting counted by the length property, but in the spirit of the length property it really should return 0, because no non-empty elements have been added to any of the arrays.

    A minimum work around is to use two nested for( in ) loops, one for the 1st array and one for the 2nd array, and to count the non-undefined elements.

    2) Extending Siamak A.Motlagh example and adding a arr([2][4]) = 'Hi Mr.C'; assignment fails with an "Uncaught TypeError: Cannot set property '4' of undefined" error.

    See the jsFiddle: http://jsfiddle.net/howardb1/zq8oL2ds/

    Here is a copy of that code:

    var arr = [[],[]];
    
    alert( arr.length );  // wrong!
    
    var c = 0;
    for( var i in arr )
      for( var j in arr[ i ] )
        if( arr[ i ][ j ] != undefined )
          ++c;
    alert( c );  // correct
    
    arr[0][2] = 'Hi Mr.A';
    alert(arr[0][2]);
    
    arr[1][3] = 'Hi Mr.B';
    alert(arr[1][3]);
    
    arr[2][4] = 'Hi Mr.C';  // At this point I'm getting VM558:62 Uncaught TypeError: Cannot set property '4' of undefined
    alert(arr[2][4]);
    
    var c = 0;
    for( var i in arr )
      for( var j in arr[ i ] )
        if( arr[ i ][ j ] != undefined )
          ++c;
    alert( c );
    

    Why does the third assignment fail? What about the [[],[]] creation statement told it that the first array was valid for 0 and 1, but not 2 or that 2 and 3 were ok for the second array, but not 4?

    Most importantly, how would I define an Array in an Array that could hold date objects in the first and second arrays. I'm using the jQuery-UI DatePicker, which expects an array of dates, as in date objects, which I've extended to use a second date array to contain date objects that contain times so I can keep track of multiple dates, and multiple times per day.

    Thanks.

提交回复
热议问题