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

问题描述 投票:0回答:1

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

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 "与数组中的值进行比较。但是这个值deep并不存在。

我试图找到解决这个问题和可能出现的类似问题的方法,因为我的变量可以像'蓝色','深蓝','深蓝的天空'。我们的工作是完全匹配的。

你会如何解决这个问题?

参见 https:/jsfiddle.netFrancesco82hg10a3wy。

javascript arrays error-handling compare title
1个回答
1
投票

你可以使用一个字符串(或RegEx)比较?

但在第一个例子中,这既符合 "蓝色",也符合 "深蓝色"(在第二个例子中,"acacalda "也符合 "acqua")。

在这些情况下,我们应该使用什么逻辑?如果与多个匹配,如果一个字数比其他字数多,就选择字数多的那个(即在这种情况下,选择 "深蓝"),如果匹配的字数相同,就选择两个字数较长的那个? 即在第二种情况下选择 "acacalda "而不是 "acqua"?(一般情况下,总是选择比较具体的答案)

见下文和 https:/jsfiddle.netalexander_Lgx83mrtL3。

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]);
}  

OUTPUT。

"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"

0
投票

我通过修改最开始的这段代码就能解决这个问题了

var fulltitle = (document.title);
var arr = fulltitle.split(':').slice(0, 1);

由于我们需要的标题部分总是在':'之前,这样一来,我就能够在不进行高级比较的情况下得到正确的结果。

© www.soinside.com 2019 - 2024. All rights reserved.