How can I create a two dimensional array in JavaScript?

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

提交回复
热议问题