Dynamically create a two dimensional Javascript Array

后端 未结 7 1819
臣服心动
臣服心动 2020-12-11 22:07

Can someone show me the javascript I need to use to dynamically create a two dimensional Javascript Array like below?

desired array contents:

7条回答
  •  死守一世寂寞
    2020-12-11 22:32

    I had a similar issue recently while working on a Google Spreadsheet and came up with an answer similar to BrianV's:

      // 1st nest to handle number of columns I'm formatting, 2nd nest to build 2d array   
      for (var i = 1; i <= 2; i++) {
        tmpRange = sheet.getRange(Row + 1, Col + i, numCells2Format); // pass/fail cells
        var d2Arr = [];
        for (var j = 0; j < numCells2Format; j++) {
          // 1st column of cells I'm formatting
          if ( 1 == i) {
            d2Arr[j] = ["center"];
          // 2nd column of cells I'm formatting
          } else if ( 2 == i ) {
            d2Arr[j] = ["left"];
          }
        }
        tmpRange.setHorizontalAlignments( d2Arr );   
      }
    

    So, basically, I had to make the assignment d2Arr[index]=["some string"] in order to build the multidimensional array I was looking for. Since the number of cells I wanted to format can change from sheet to sheet, I wanted it generalized. The case I was working out required a 15-dimension array. Assigning a 1-D array to elements in a 1-D array ended up making the 15-D array I needed.

提交回复
热议问题