[英]indexOf not working in Google Apps Script
我正在制作一個Google表格文檔,用於分析我的銀行交易記錄。 我的許多交易說明都以相同的字母開頭,尤其是“ SIG”(正確的大小寫)。 我想計算這些交易的數量,但不能。
為了進行故障排除,我確保僅檢查一個單元格/輸入時indexOf可以工作。 如果在單元格中找不到“ SIG”,則返回“ -1”;如果在單元格的開頭找到“ SIG”,則返回“ 0”。
再次進行故障排除,我還確保我正確地循環了一個數組(多個單元格),該數組僅計算非空單元格的數量。 那也行。
當我嘗試將所有內容放在一起時,我無法使其正常工作,我也不知道為什么。 簡短功能如下。 謝謝您的幫助。
function SIG_counter (descriptions) {
var SIG_total = 0;
var SIG_checker;
for (var i=0; i<descriptions.length; i++) {
var SIG_checker = descriptions[i].indexOf("SIG");
Logger.log(descriptions[i]);
Logger.log(SIG_checker);
if (SIG_checker == 0.0) {
SIG_total++;
}
}
return SIG_total;
}
var sample_array = ["Funds Added (Donation)",
"SIG POS purchase at Paypal",
"PIN POS purchase cashback",
"PIN POS purchase cashback",
"SIG POS purchase at Paypal"]
function trouble_shooter () {
SIG_counter(sample_array);
}
日志:
[18-01-28 15:30:54:630 PST] Funds Added (Donation)
[18-01-28 15:30:54:630 PST] -1.0
[18-01-28 15:30:54:631 PST] SIG POS purchase at Paypal
[18-01-28 15:30:54:631 PST] 0.0
[18-01-28 15:30:54:632 PST] PIN POS purchase cashback
[18-01-28 15:30:54:632 PST] -1.0
[18-01-28 15:30:54:632 PST] PIN POS purchase cashback
[18-01-28 15:30:54:633 PST] -1.0
[18-01-28 15:30:54:633 PST] SIG POS purchase at Paypal
[18-01-28 15:30:54:634 PST] 0.0
當列(Ex:B1:B22)作為自定義函數的輸入時,范圍將轉換為2D數組並傳遞給該函數。 如果您輸入一行(例如B9:F9),則會將其轉換為一維數組。 在這種情況下,您將一列傳遞到函數中,因此將其轉換為2D數組。 因此,coressponding示例數組應如下所示:
var sample_array = [["Funds Added (Donation)"],
["SIG POS purchase at Paypal"],
["PIN POS purchase cashback"],
["PIN POS purchase cashback"],
["SIG POS purchase at Paypal"]]
並且您將需要為第二維提供索引,就像descriptions[i][0]
,其中[i]
代表第一維, [0]
代表第二維。 因此,如果您的示例數組
sample_array[0][0] = "Funds Added (Donation)"
sample_array[1][0] = "SIG POS purchase at Paypal"
等等。
您修改后的函數如下所示:
function SIG_counter (descriptions) {
var SIG_total = 0;
var SIG_checker="";
if(descriptions.map){ //Check if the arugment is array
//This code assumess it is always a 2D or a single value
for (var i=0; i<descriptions.length; i++) {
SIG_checker = descriptions[i][0].indexOf("SIG");
Logger.log(descriptions[i][0]);
Logger.log(SIG_checker);
if (SIG_checker == 0.0) {
SIG_total++;
}
} } else { //if arugment is not array, it refers to a single cell
if(descriptions.indexOf("SIG") == 0.0){
SIG_total = 1
}
}
return SIG_total;
}
請遵循此文檔以獲取更多參考。
最后說明:僅當選擇了列或單個單元格時,以上功能才起作用。 如果選擇了一行,將會報錯!
編輯:等效地,您可以使用此內置函數來執行相同的操作
=Arrayformula(sum(iferror(find("SIG",B1:B200),0)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.