gpt4 book ai didi

javascript - 未定义传递给数组

转载 作者:行者123 更新时间:2023-12-01 11:11:19 24 4
gpt4 key购买 nike

我有测验应用程序的代码。问题是,undefined 以某种方式传递给数组 choices

'use strict';

var quiz,
actualQuestion = 1,
getChoices,
generateHtml,
html = '',
choices = [];

quiz = [{
question: "Who is Prime Minister of the United Kingdom?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer: 0
}, {
question: "Who is Prime Minister of the United Kingdom2?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer: 0
}];

getChoices = function() {
for (var i = 0; i < quiz[actualQuestion].choices.length; i++) {
choices[i] += quiz[actualQuestion].choices[i];
console.log(choices[i]);
}
}

generateHtml = function() {
for (var i = 0; i < choices.length; i++) {
html += '<label>' +
'<input type="radio" name="answer">' +
choices[i] +
'</label>';
}
}

getChoices();
generateHtml();

document.getElementById('answers').innerHTML = html;
console.log(
html
);
<form id="quiz">
<div id="question">

</div>
<div id="answers">

</div>
<input type="button" value="Next">
</form>

最佳答案

问题是 choices[i] += quiz[actualQuestion].choices[i];choices[i] 的值未定义,因为您正在定义一个空数组,所以你有 choices[i] = undefined + quiz[actualQuestion].choices[i];

只需将其更改为 choices[i] = quiz[actualQuestion].choices[i];

'use strict';

var quiz,
actualQuestion = 1,
getChoices,
generateHtml,
html = '',
choices = [];

quiz = [{
question: "Who is Prime Minister of the United Kingdom?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer: 0
}, {
question: "Who is Prime Minister of the United Kingdom2?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer: 0
}];

getChoices = function() {
for (var i = 0; i < quiz[actualQuestion].choices.length; i++) {
choices[i] = quiz[actualQuestion].choices[i];
console.log(choices[i]);
}
}

generateHtml = function() {
for (var i = 0; i < choices.length; i++) {
html += '<label>' +
'<input type="radio" name="answer">' +
choices[i] +
'</label>';
}
}

getChoices();
generateHtml();

document.getElementById('answers').innerHTML = html;
console.log(
html
);
<form id="quiz">
<div id="question">

</div>
<div id="answers">

</div>
<input type="button" value="Next">
</form>

关于javascript - 未定义传递给数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32138939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com