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