微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何检查数组是否包含特定值 google Apps Script

如何解决如何检查数组是否包含特定值 google Apps Script

我正在使用 range.getValues() 在 Google Apps 脚本中加载一个数组。 我想遍历数组并在数组包含我要查找的值时执行某些操作。

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

问题是当我使用这个方法时,数组包含另一个数组,所以 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");
    }
  });
}

这是我从中获取所有数组值的示例表:

enter image description here

结果如下:

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。