簡體   English   中英

Google Sheets App Script中數組的長度

[英]Length of an array in Google Sheets App Script

我正在嘗試確定數組的長度,以便可以使用長度來確定 for 循環需要迭代多少次。

我正在嘗試從多列中的 1 行讀取以確定需要寫入哪些單元格。 代碼會將數據寫入行,但需要確定 header 是否已寫入,或者 header 是否也需要寫入。 在這個 function 中,我專注於檢查標題以查看值是否已寫入。

我知道范圍值 D2:Z2 效率低下,我願意接受另一種解決方法。 我很想知道是否有人能夠確定為什么長度是 1.0 而不是 4,如果其他人能想出一種比較值的方法,然后確定寫入新標題集的列。

代碼

 function getCurrentHeader() {

  //gets active spreadsheet, saves to array
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Records");
  var rangeValues = Array;
  //D2:Z2 is the current largest range available 15/12/21 
  rangeValues = sheet.getRange("D2:Z2").getValues(); 
  return rangeValues;
}


function checkCurrentHeaders(){
  //gets the array of headers
  var current = getCurrentHeader();
  //Logger.log(current);
  var leng = current.length;

  Logger.log(leng);

}

以上是我到目前為止所寫的內容,但即使記錄了數組以查看值,the.length 返回值 1,數組中有 4 個值,所以我期待 4 作為返回值。 我還注意到 output 在兩組方括號中。 請參閱下面的日志信息。

記錄器

11:52:32 AM Notice  Execution started
11:52:32 AM Info    [[B, A, C, DF, , , , , , , , , , , , , , , , , , , ]]
11:52:32 AM Info    1.0
11:52:32 AM Notice  Execution completed

getValues()返回二維數組。 在您的腳本中, rangeValues = sheet.getRange("D2:Z2").getValues()是二維數組,如[[D2, E2, F2,,,]] 這樣,當您檢查var current = getCurrentHeader()current.length時,將返回1 在這種情況下, 1是行數。 我認為這是您的問題的原因。

當您要檢索列數時,請進行如下修改。

從:

var leng = current.length;

至:

var leng = current[0].length;

或者

從:

rangeValues = sheet.getRange("D2:Z2").getValues(); 

至:

rangeValues = sheet.getRange("D2:Z2").getValues()[0];

或者

從:

rangeValues = sheet.getRange("D2:Z2").getValues(); 

至:

rangeValues = sheet.getRange("D2:Z2").getValues()[0].filter(String); // In this case, the empty cells are ignored.

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM