【问题标题】:Looping through an array of objects in quiz app在测验应用程序中循环遍历一组对象
【发布时间】:2019-11-25 18:52:49
【问题描述】:

我创建了一个测验应用程序并遇到了一些问题,幸运的是我解决了问题,但我只是好奇。所以问题是我有一个包含问题和答案的数组。当我单击下一个按钮时,我想遍历数组并显示下一个问题。问题是当我点击下一个按钮时什么也没发生,只显示最后一个问题

这是一个示例代码

const questions = [

{
question: "What is 2 + 2?",
answers: [3,4,5,6]
},
{
question: "What is 6 + 2?",
answers: [9,8,5,6]

},
{
question: "What is 10 + 30?",
answers: [32,45,40,34]

}

]

const p = document.getElementById("qtn");
document.getElementById("next").addEventListener("click",()=> {

for (let i=0; i<questions.length;i++){

p.textContent = questions[i].question;
}

});

但是当我删除 for 循环时它起作用了

const i=0;
const p = document.getElementById("qtn");
document.getElementById("next").addEventListener("click",()=> {



p.textContent = questions[i].question;
i++

});

那么为什么第二个解决方案有效但第一个解决方案无效

【问题讨论】:

  • "...只显示第一个问题" - 你确定不是最后一个 问题吗?第一个示例中的循环不是必需的。每次单击时,它都会将文本设置为所有问题一个接一个。最后一个将始终是显示的,因为它是循环中的最后一个。查看this example 中的控制台以获得更清晰的演示。
  • 是的,对不起,我的意思是最后一个问题。我会更新问题

标签: javascript arrays object for-loop dom


【解决方案1】:

实际上,在您的第一个解决方案中,唯一显示的答案是最后一个。

发生这种情况的原因是for 循环的结果总是相同的。它没有任何目的。

每次按下 next 时,for 循环将从 i = 0 运行到 questions.length。这意味着它会一直运行到循环结束,并在循环的每次迭代中非常快速地更改 p.textContent 的值。因此,您会看到的唯一结果是最后一条消息(循环结束后)。

当您删除循环后,您的代码只会在每次单击后递增,因此会显示所需的结果。另外对于计数器,我会使用let i= 0; 而不是const

希望它能为你澄清事情。

【讨论】:

  • 谢谢。只是为了澄清一下,我也不能使用 foreach、for(..of) 等?
  • 我的意思是,在这种情况下使用它没有意义,因为您一次需要一个迭代
【解决方案2】:

如果不是数组或对象,则不能将值更新为const,请改用varlet

const questions = [
{
question: "What is 2 + 2?",
answes: [3,4,5,6]
},
{
question: "What is 6 + 2?",
answes: [9,8,5,6]

},
{
question: "What is 10 + 30?",
answes: [32,45,40,34]
}
];

var p = document.getElementById("qtn");
var current=0;
var questionIndex=current+1;

p.innerHTML = '('+ questionIndex +')  '+questions[current].question;

var prevButton=document.getElementById("prev");
var nextButton=document.getElementById("next");

function nextQuestion(){

if(current<questions.length-1){
current++;
questionIndex=current+1;
p.innerHTML = '('+ questionIndex +')  '+questions[current].question;
prevButton.style.display="block";
}

if(current===questions.length-1){
prevButton.style.display="block"
nextButton.style.display = "none";
}

}


function prevQuestion(){
if(current>0){
current--;
questionIndex=questionIndex-1;
p.innerHTML = '('+ questionIndex +')  '+questions[current].question;
nextButton.style.display="block";
}

if(current===0){
prevButton.style.display="none"
nextButton.style.display = "block";
}
}
<p id="qtn"></p>
<button id="prev" style="display:none" onclick="prevQuestion()">Prev</button>
<button id="next" style="display:block" onclick="nextQuestion()">Next</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 2017-01-29
    • 2015-10-15
    相关资源
    最近更新 更多