简体   繁体   中英

How can I create a javascript array froma range in a google sheet?

I want to take a range from a Google spreadsheet, create a javascript array and then pass each item, form the range, into the array.

The values in the range (A5: A10) are, for example, bitcoin-cash, litecoin, ethereum, monero, dash, quantstamp.

My code is as follows:

function appendCoins() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var r = sheet.getRange('A5:A10').getValues();
  var coins = [];
  for (var i=0;i < r.length-1;i++) {
     coins.push(r[0][i]);
    }
    Logger.log(coins)
}

The logger shows me this:

[18-01-10 18:09:07:218 GMT] [bitcoin-cash, null, null, null, null, null]

So the first one is correct, it loops the correct number of times but all the other values are undefined.

Why is this? It should be straightforward. Can anybody help? Thank you.

getValues returns the range indexed by row, then column. Your range, A5:A10, has five rows and one column. You're treating it as though it had one row and five columns. Swap 0 and i in your code:

function appendCoins() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var r = sheet.getRange('A5:A10').getValues();
  var coins = [];
  for (var i=0;i < r.length-1;i++) {
     coins.push(r[i][0]);
  }
  Logger.log(coins)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM