【问题标题】:indexof() partial match issueindexof() 部分匹配问题
【发布时间】:2023-04-02 20:36:01
【问题描述】:

在 Google App Script 中编写一个简单的网站

在谷歌表格中有一个电子表格 - 2 列 - 第一个有名词和第二个描述性词

有些事情是这样的:

第 1 列 - 第 2 列

桌子 - 木头

球 - 塑料

椅子 - 金属蓝色

我的代码在第 2 列中搜索关键字并从第 1 列返回匹配项。当第 2 列中有一个单词时它工作正常,但当有更多单词时就不行了......所以搜索“wood”返回 table,搜索“plastic”返回 ball,但搜索“metal”返回任何内容,“blue”相同

任何想法如何解决这个问题?

 function FilterResults(keyword){
  
  //connect with spreadsheet
  var ss = SpreadsheetApp.openByUrl(url);
  var ws = ss.getSheetByName("sheet1");
  var sheetData = ws.getRange(1,1,ws.getRange("A1").getDataRegion().getLastRow(),5).getValues();
  
  //create arrays of values from cells in each column   
   var Column1List = sheetData.map(function(r){return r[0]; });
   var Column2List = sheetData.map(function(r){return r[1]; });
   
   
   //make sure search tags are in string format
   var x = keyword.toString();
   
   //find 1st row(position) that has tag in it
   var position = Column2List.indexOf(x);
   
     if (position > -1){
   
   //if the search found a match return cell content according to row number
     return Column1List[position];
   }else{
     return "unavailable";
   }

【问题讨论】:

  • 如果有两个或多个关键字,您的Column2List 是什么样的?你试过控制台记录吗?
  • 它只包含由空格分隔的单词...数组的日志返回“木头、塑料、金属蓝色等...”

标签: javascript google-apps-script indexof


【解决方案1】:

您的问题在var position = Column2List.indexOf(x); 行,indexOf 返回完全匹配,您应该使用 findIndex 并传递一个函数来搜索您的关键字:

var position = Column2List.findIndex( s => s.indexOf(x) >= 0 )

编辑:

如果你想在某个索引之后找到一个索引,切片会复制数组,解决方法是在函数中添加一个条件:(s, i) => i >= index && s.indexOf(x) >= 0

但如果我理解正确,您可以简单地在sheetData 上使用.filter

sheetData.filter(r => r[1].indexOf(keyword) >= 0 )

【讨论】:

  • 感谢您的解决方案 - 它有效,但给我带来了另一个问题......我需要在循环中运行它以查找具有匹配关键字的所有行 - 我使用 while{} 和 indexOf()我可以指定一个开始位置(从 vefore 找到的位置在每个循环中更新) - 我无法弄清楚如何让 findIndex 在特定索引处开始搜索......我猜我可以使用切片但有十几个匹配的结果一个 1000 多行的表,它可能是一个真正的猪......
  • 我改进了答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-14
  • 2015-09-18
  • 1970-01-01
  • 2020-02-07
相关资源
最近更新 更多