为了账号安全,请及时绑定邮箱和手机立即绑定

检查无线电输入时我的 if 语句不起作用

检查无线电输入时我的 if 语句不起作用

开心每一天1111 2023-07-29 13:09:30
我正在尝试验证无线电输入以检查其答案是否正确。但它跳过了线if (answer == allQuestions[q].correctAnswer)这是完整代码https://jsfiddle.net/alcatel/sopfmevh/1/for (let k = 0; k < answers.length; k++) {  if (answers[k].checked) {    answer = answers[k].value;  }}// IT SKIPS THIS LINE !!if (answer == allQuestions[q].correctAnswer) { // IT SKIPS THIS LINE!!  alert("correct");}q++;    populate();
查看完整描述

3 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

我认为你的 If 语句应该看起来像这样

if(answer == allQuestions[q].choices[allQuestions[q].correctAnswer]) {
        alert("correct");
    }

编辑了这个,刚刚尝试并为我工作


查看完整回答
反对 回复 2023-07-29
?
jeck猫

TA贡献1909条经验 获得超7个赞

您还可以使用数组中元素的索引进行比较。


if(allQuestions[q].choices.indexOf(answer) == allQuestions[q].correctAnswer) {

    alert("correct");

}


查看完整回答
反对 回复 2023-07-29
?
动漫人物

TA贡献1815条经验 获得超10个赞

因为我做到了...


const allQuestions = 

        [ { question     : 'Where is Helsinki?'

          , choices      : [ 'Sweden', 'Finland', 'Us' ] 

          , correctAnswer: 1

          } 

        , { question     : 'Where is Stockholm?'

          , choices      : [ 'Norway', 'Iceland', 'Sweden' ] 

          , correctAnswer: 2

          } 

        , { question     : 'Where is Köpenhamn?'

          , choices      : [ 'Denmark', 'Sweden', 'Norway' ] 

          , correctAnswer: 0

          } 

        ] 

function* qList(arr) { for (let q of arr) yield q }


const libQuestion  = document.querySelector('h1')

  ,   formReplies  = document.getElementById('list')

  ,   btNext       = document.querySelector('button')

  ,   DomParser    = new DOMParser()

  ,   qListRead    = qList( allQuestions )

  ,   score        = { correct: 0, count:0 }

  ;

var currentAnswer = ''

  ;

function setNewQuestion()

  {

  formReplies.innerHTML = ''


  let newQuestion = qListRead.next()

  if (!newQuestion.done)

    {

    libQuestion.textContent = newQuestion.value.question

    currentAnswer           = newQuestion.value.correctAnswer

    ++score.count

    newQuestion.value.choices.forEach((choice,indx)=>

      {

      let line = `<label><input type="radio" name="answer" value="${indx}">${ choice}</label>`

        , inLn = (DomParser.parseFromString( line, 'text/html')).body.firstChild

        ;

      formReplies.appendChild(inLn)

      })

    }

  else

    {

    libQuestion.textContent = ` Score = ${score.correct} / ${score.count}`

    btNext.disabled         = true

    }

  }

setNewQuestion()

btNext.onclick=()=>

  {

  if (formReplies.answer.value)

    {

    score.correct += ( currentAnswer == formReplies.answer.value )

    setNewQuestion()

    }

  }

<h1></h1>

<p></p>

<form id="list"></form>

<br>

<button>next</button>


查看完整回答
反对 回复 2023-07-29
  • 3 回答
  • 0 关注
  • 92 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信