Array.map( ) 只适用于第一个数组,而不适用于第二个数组。有人可以解释为什么它不起作用并提供适当的解决方案



我有两个数组,每个数组都被映射过来,如果数组与"apiSuggestion"不匹配,则元素将获得带有红色文本的黑色背景色。 这有效:

let sentenceOne = ["somthing", "life", "nothing"];
let sentenceTwo = ["nummber", "seven", everythng"];
let apiSuggestion = ["something", "life", "nothing", "number", "seven", "everything"];
let matchMakerOne = sentenceOne.map(function(word,index){
if( word !== apiSuggestion[index]){
return `
<span style="background-color:black; color:red">
${word}
</span>
} else {
return word
}
})
document.getElementById("sentenceOne").innerHTML = machMakerOne.join(' ')
//in the HTML i see "somthing" highlighted in black background-color with red text, as it doesnt match to api suggesstion

即使逻辑相同,这也行不通,我在哪里犯了错误?

let matchMakerTwo = sentenceTwo.map(function(word,index){
if( word !== apiSuggestion[index]){
return `
<span style="background-color:black; color:red">
${word}
</span>
} else {
return word
}
})
document.getElementById("sentenceTwo").innerHTML = machMakerTwo.join(' ')
// "nummber", "seven", everythng" all get black background and red text
// nummber and everythng should get black background and red text

我试图"连接"句子一和句子二,它只捕获第一个数组的拼写错误,而不是第二个数组的拼写错误。如何突出显示这两个数组中的拼写错误并在 HTML 中呈现它?任何帮助,不胜感激。提前谢谢你。 我创建了JSFiddle

@Thakur是正确的 - 在这两种情况下,您都只检查apiSuggestion数组的前三个元素。

取代

if (word !== apiSuggestion[index]) {...}

if (apiSuggestion.indexOf(word) === -1) {...}

如果arg不是目标数组的元素,则返回-1Array.indexOf(arg)

参考: MDN: Array.prototype.indexOf((

代码工作正常。如果项的值与 apiSuggestion 中同一索引中的项不匹配,则在返回彩色文本时循环数组中的每个项。

第一句:

sentenceOne[0] (somthing) | apiSuggestion[0] (something) - NOT
sentenceOne[1] (life) | apiSuggestion[1] (life) - MATCH
sentenceOne[2] (nothing) | apiSuggestion[2] (nothing) - MATCH

第二句:

sentenceTwo[0] (nummber) | apiSuggestion[0] (something) - NOT
sentenceTwo[1] (seven) | apiSuggestion[1] (life) - NOT
sentenceTwo[2] (everythng) | apiSuggestion[2] (nothing) - NOT

我相信您要实现的是,如果迭代中的当前项不在 apiAdvice 数组中,则返回彩色文本。您可以使用includes方法实现此目的。您的函数应该是:

let matchMakerTwo = sentenceTwo.map(function(word) {
if (!apiSuggestion.includes(word)) {
return `
<span style="background-color:black; color:red">
${word}
</span>
`
} else {
return word
}
})

PS:您可以在问题中嵌入代码片段。这样,您的问题就会变得更清晰,并且具有工作模型。

最新更新