仅适用于第一个数组,而不适用于第二个数组。有人可以解释为什么它不起作用并提供适当的解决方案吗?

我有两个数组,每个数组都被映射过来,如果数组与“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 中?任何帮助是值得赞赏的。提前感谢您。我创建了JS小提琴


富国沪深
浏览 138回答 2
2回答

ITMISS

在这两种情况下,您只检查数组的前三个元素。apiSuggestion取代if&nbsp;(word&nbsp;!==&nbsp;apiSuggestion[index])&nbsp;{...}跟if&nbsp;(apiSuggestion.indexOf(word)&nbsp;===&nbsp;-1)&nbsp;{...}Array.indexOf(arg)如果 不是目标数组的元素,则返回。-1arg参考:&nbsp;MDN: 数组.prototype.索引的()

素胚勾勒不出你

代码工作正常。如果数组中的每个项目的值与 apiSuggestion 中同一索引中的项目不匹配,则循环访问该数组中的每个项目,以返回彩色文本。第一句:sentenceOne[0] (somthing) | apiSuggestion[0] (something) - NOTsentenceOne[1] (life) | apiSuggestion[1] (life) - MATCHsentenceOne[2] (nothing) | apiSuggestion[2] (nothing) - MATCH第二句:sentenceTwo[0] (nummber) | apiSuggestion[0] (something) - NOTsentenceTwo[1] (seven) | apiSuggestion[1] (life) - NOTsentenceTwo[2] (everythng) | apiSuggestion[2] (nothing) - NOT我相信您要实现的是,如果迭代中的当前项不在 apiSuggestion 数组中,则返回彩色文本。您可以使用该方法实现该方法。您的函数应为:includeslet matchMakerTwo = sentenceTwo.map(function(word) {&nbsp; &nbsp; if (!apiSuggestion.includes(word)) {&nbsp; &nbsp; &nbsp; &nbsp; return `&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="background-color:black; color:red">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ${word}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; &nbsp; &nbsp; `&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; return word&nbsp; &nbsp; }})PS:您可以在问题中嵌入代码片段。通过这种方式,您的问题变得更加清晰,并具有工作模型。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript