繁体   English   中英

如何检查数组是否包含某些值 google Apps Script

[英]How to check whether array includes certain value google Apps Script

我正在使用 range.getValues() 在 Google Apps 脚本中加载一个数组。 如果数组包含我正在寻找的值,我想遍历数组并做一些事情。

if (array.include("abc")){*doSomething*}

问题是当我使用这种方法时,数组包含另一个 arrays,所以 array.include() 不起作用。 我可以使用这样的解决方法:

for (var i = 0; i<=array.length; i++){ 
  if (array[i] == "abc"){*doSomething*}

我想知道有没有更好的方法来做到这一点? 我尝试使用 array.indexOf() 但它为第 0 个值返回 -1,这很奇怪

function find() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet1');
  const haystack=sh.getDataRange().getValues();
  const needle="44";
  let found = false;
  haystack.forEach(r=>{
    r.forEach(c=>{
      if(c==needle) {
        found=true;
      }
    })
  });
  if(found) {
    SpreadsheetApp.getUi().alert('Needle was found in haystack');
  }
}

或者

function find() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet1');
  const haystack=sh.getDataRange().getValues();
  const needle="44";
  let found = false;
  haystack.forEach(r=>{
    if(~r.indexOf(needle)) {
      found=true;
    }
  });
  if(found) {
    SpreadsheetApp.getUi().alert('Needle was found in haystack');
  }
}

建议

或者,您也可以尝试这种方式:

function arrayCheck(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var arr = ss.getDataRange().getValues(); //Get all values from sheet
  Logger.log(arr);
  arr.forEach(function(res) {
    if(res == 'abc'){
      Logger.log("Found a match");
      //do something
    }else{
      Logger.log(res+" does not match abc");
    }
  });
}

这是一个样本表,我从中获得了所有数组值:

在此处输入图像描述

结果如下:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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