Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

google apps script - creating 2 dimension arrays

I am new to JS and need some basic help:

I have a spreadsheet which has a square matrix of data.

I can read these data as follows:

  var freqArr     = new Array(new Array());
  var freqSheet   = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("freq");
  var freqRows    = freqSheet.getDataRange();
  var freqNumRows = freqRows.getNumRows();
  freqArr = freqSheet.getRange(2, 2, freqNumRows, freqNumRows).getValues();

I now want to create a an array in memory similar to the one I have read from the sheet

 var tempArr = new Array(new Array());
  for (var i = 0; i <= 3; i++) {
    for (var j = 0; j <= 3; j++) {        
      tempArr [i][j] = freqArr[i][j] ;
    }
  }

As soon as j incs from 0 to 1 and I try to store anything in tempArr [i][j] I get an error "TypeError: Cannot set property "0.0" of undefined to "xxx"

I have tried every combination of creating tempArr that I can think of plus a few more.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Someone much smarter than myself could probably help you write this better, but the way it looks to me is that you want to create tempArr as the main array, which would have 2 arrays inside of it.

Inside of each of those arrays are values, so:

// result: tempArr = [[1,2],[4,5]]
tempArr = [] // or new Array
for (var i = 0; i <= 3; i++) {
  tempArr[i] = [];
  for (var j = 0; j <= 3; j++) {        
    tempArr[i].push(freqArr[i][j]);
  }
}

You create your first main array in tempArr, within your for, each time you loop through, tempArr[i] is created as an array, and inside of the second for, you want to push the value of freqArr to the inner array.

UPDATE Had a space in tempArr[i] that would've caused it to not work for sure. Sorry!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...