How can I create a two dimensional array in JavaScript?

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

    How to create an empty two dimensional array (one-line)

    Array.from(Array(2), () => new Array(4))
    

    2 and 4 being first and second dimensions respectively.

    We are making use of Array.from, which can take an array-like param and an optional mapping for each of the elements.

    Array.from(arrayLike[, mapFn[, thisArg]])

    var arr = Array.from(Array(2), () => new Array(4));
    arr[0][0] = 'foo';
    console.info(arr);

    The same trick can be used to Create a JavaScript array containing 1...N


    Alternatively (but more inefficient 12% with n = 10,000)

    Array(2).fill(null).map(() => Array(4))
    

    The performance decrease comes with the fact that we have to have the first dimension values initialized to run .map. Remember that Array will not allocate the positions until you order it to through .fill or direct value assignment.

    var arr = Array(2).fill(null).map(() => Array(4));
    arr[0][0] = 'foo';
    console.info(arr);


    Follow up

    Here's a method that appears correct, but has issues.

     Array(2).fill(Array(4)); // BAD! Rows are copied by reference
    

    While it does return the apparently desired two dimensional array ([ [ <4 empty items> ], [ <4 empty items> ] ]), there a catch: first dimension arrays have been copied by reference. That means a arr[0][0] = 'foo' would actually change two rows instead of one.

    var arr = Array(2).fill(Array(4));
    arr[0][0] = 'foo';
    console.info(arr);
    console.info(arr[0][0], arr[1][0]);

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

    I found below is the simplest way:

    var array1 = [[]];   
    array1[0][100] = 5; 
    
    alert(array1[0][100]);
    alert(array1.length);
    alert(array1[0].length);
    
    0 讨论(0)
  • 2020-11-21 05:28

    The easiest way:

    var myArray = [[]];
    
    0 讨论(0)
  • 2020-11-21 05:28

    This is what i achieved :

    var appVar = [[]];
    appVar[0][4] = "bineesh";
    appVar[0][5] = "kumar";
    console.log(appVar[0][4] + appVar[0][5]);
    console.log(appVar);

    This spelled me bineeshkumar

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

    var playList = [
      ['I Did It My Way', 'Frank Sinatra'],
      ['Respect', 'Aretha Franklin'],
      ['Imagine', 'John Lennon'],
      ['Born to Run', 'Bruce Springsteen'],
      ['Louie Louie', 'The Kingsmen'],
      ['Maybellene', 'Chuck Berry']
    ];
    
    function print(message) {
      document.write(message);
    }
    
    function printSongs( songs ) {
      var listHTML;
      listHTML = '<ol>';
      for ( var i = 0; i < songs.length; i += 1) {
        listHTML += '<li>' + songs[i][0] + ' by ' + songs[i][1] + '</li>';
      }
      listHTML += '</ol>';
      print(listHTML);
    }
    
    printSongs(playList);

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

    Few people show the use of push:
    To bring something new, I will show you how to initialize the matrix with some value, example: 0 or an empty string "".
    Reminding that if you have a 10 elements array, in javascript the last index will be 9!

    function matrix( rows, cols, defaultValue){
    
      var arr = [];
    
      // Creates all lines:
      for(var i=0; i < rows; i++){
    
          // Creates an empty line
          arr.push([]);
    
          // Adds cols to the empty line:
          arr[i].push( new Array(cols));
    
          for(var j=0; j < cols; j++){
            // Initializes:
            arr[i][j] = defaultValue;
          }
      }
    
    return arr;
    }
    

    usage examples:

    x = matrix( 2 , 3,''); // 2 lines, 3 cols filled with empty string
    y = matrix( 10, 5, 0);// 10 lines, 5 cols filled with 0
    
    0 讨论(0)
提交回复
热议问题