Declare an empty two-dimensional array in Javascript?

后端 未结 18 1365
暖寄归人
暖寄归人 2020-11-29 21:45

I want to create a two dimensional array in Javascript where I\'m going to store coordinates (x,y). I don\'t know yet how many pairs of coordinates I will have because they

相关标签:
18条回答
  • 2020-11-29 22:42

    Create an object and push that object into an array

     var jSONdataHolder = function(country, lat, lon) {
    
        this.country = country;
        this.lat = lat;
        this.lon = lon;
    }
    
    var jSONholderArr = [];
    
    jSONholderArr.push(new jSONdataHolder("Sweden", "60", "17"));
    jSONholderArr.push(new jSONdataHolder("Portugal", "38", "9"));
    jSONholderArr.push(new jSONdataHolder("Brazil", "23", "-46"));
    
    var nObj = jSONholderArr.length;
    for (var i = 0; i < nObj; i++) {
       console.log(jSONholderArr[i].country + "; " + jSONholderArr[i].lat + "; " + 
       jSONholderArr[i].lon);
    
    }
    
    0 讨论(0)
  • 2020-11-29 22:43

    No need to do so much of trouble! Its simple

    This will create 2 * 3 matrix of string.

    var array=[];
    var x = 2, y = 3;
    var s = 'abcdefg';
    
    for(var i = 0; i<x; i++){
        array[i]=new Array();
          for(var j = 0; j<y; j++){
             array[i].push(s.charAt(counter++));
            }
        }
    
    0 讨论(0)
  • 2020-11-29 22:44

    // for 3 x 5 array

    new Array(3).fill(new Array(5).fill(0))
    
    0 讨论(0)
  • 2020-11-29 22:46

    var arr = [];
    var rows = 3;
    var columns = 2;
    
    for (var i = 0; i < rows; i++) {
        arr.push([]); // creates arrays in arr
    }
    console.log('elements of arr are arrays:');
    console.log(arr);
    
    for (var i = 0; i < rows; i++) {
        for (var j = 0; j < columns; j++) {
            arr[i][j] = null; // empty 2D array: it doesn't make much sense to do this
        }
    }
    console.log();
    console.log('empty 2D array:');
    console.log(arr);
    
    for (var i = 0; i < rows; i++) {
        for (var j = 0; j < columns; j++) {
            arr[i][j] = columns * i + j + 1;
        }
    }
    console.log();
    console.log('2D array filled with values:');
    console.log(arr);

    0 讨论(0)
  • 2020-11-29 22:47

    If we don’t use ES2015 and don’t have fill(), just use .apply()

    See https://stackoverflow.com/a/47041157/1851492

    let Array2D = (r, c, fill) => Array.apply(null, new Array(r)).map(function() {return Array.apply(null, new Array(c)).map(function() {return fill})})
    
    console.log(JSON.stringify(Array2D(3,4,0)));
    console.log(JSON.stringify(Array2D(4,5,1)));

    0 讨论(0)
  • 2020-11-29 22:48

    You can nest one array within another using the shorthand syntax:

       var twoDee = [[]];
    
    0 讨论(0)
提交回复
热议问题