javascript - 比较标题字段和数组时避免错误

标签 javascript arrays error-handling compare title

以下代码从页面标题中获取第一个单词,将其与数组的值进行比较,并向我输出最终值:

var fulltitle = "Deep Blue Shoes";
var arr = fulltitle.split(' ').slice(0, 1);
var title = arr && arr.length ? arr[0] : "";

//test variables 
testarray = ["blue", "top", "110", "in stock", "deep blue", "down", "111", "in stock"]

//function
function testfunction(array, variable) {
  var varindex = array.indexOf(variable.toLowerCase())
  return array[varindex + 2]
}

//calling the function
var finalvalue = testfunction(testarray, title);

console.log( finalvalue )


在这种情况下,如果我的标题是Deep Blue shoes,那么系统会过早剪切标题,并尝试将“deep”值与数组中的值进行比较。但是深层值(value)并不存在。

我正在努力寻找解决方案,并且可能会出现类似的问题,因为我的变量可能像“蓝色”,“深蓝色”,“深蓝色天空”。我们仅使用完全匹配。

您将如何解决?

另请参阅https://jsfiddle.net/Francesco82/hg10a3wy/

最佳答案

您可以使用String(或RegEx)比较吗?

但是在第一个示例中,它与“蓝色”以及“深蓝色”(在第二个“acquacalda”以及“acqua”中)匹配。

在这种情况下,我们应该使用什么逻辑?如果匹配的单词不止一个,则选择一个单词最多的单词(如果一个单词的单词比另一个单词多)(即,在这种情况下,选择“深蓝色”),如果匹配的单词数量相同,则选择更长的单词。这两个字?即在第二种情况下,选择“acquacalda”而不是“acqua”? (通常,总是选择更具体的答案)

参见下文和https://jsfiddle.net/alexander_L/gx83mrtL/3/

findPage("Deep Blue Shoes");
findPage("Acquacalda");

function findPage(fulltitle){
  //test variables 
  const testarray = ["blue", "top", "110", "in stock", "deep blue", "down", "111", "in stock", "acqua", "top", "112", "in stock", "acquacalda", "down", "113", "in stock"]

  const altMatches = testarray.reduce((aggArr, item) => {
    if (fulltitle.toLowerCase().includes(item)){
      console.log('we have a match with ' + item);   
      aggArr.push(item);
    }
    return aggArr;
  }, []);

  //then we can choose the "largest" match:
  const finalMatch = altMatches.reduce((aggMatch, item) => {
    if (aggMatch == null || (aggMatch.split(' ').length < item.split(' ').length) || (aggMatch.length < item.length)){
      return item;
    }
    return aggMatch;
  }, null);

  console.log('the final match is ' + finalMatch);

  const finalPage = testarray.indexOf(finalMatch) + 2;
  console.log('the final match page number is ' + testarray[finalPage]);
}  


输出:

"we have a match with blue"
"we have a match with deep blue"
"the final match is deep blue"
"the final match page number is 111"

"we have a match with acqua"
"we have a match with acquacalda"
"the final match is acquacalda"
"the final match page number is 113"

关于javascript - 比较标题字段和数组时避免错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62170864/

相关文章:

javascript - 如何向 jqxwidget 部分饼图系列添加自定义工具提示?

vba - 合并功能在VBA中不起作用

php - 打开/处理 580GB 错误日志文件的建议

javascript - 将 css 框阴影字符串解析为单独的值

javascript - 根据数据库中的值将 css 应用于从数据库中检索的元素

javascript - HTML DIV 位于 DIV 之上的 DIV 内

上传前 JavaScript 验证文件名

java - 如何使用 Java 将两个或多个多维数组合并为单个多维数组

c++ - 删除数组指针堆损坏

angularjs - 即使不在form字段中输入数据,也会执行angularjs错误处理