gpt4 book ai didi

javascript - 我在 JavaScript 中遇到了未定义的问题,并且不明白为什么

转载 作者:行者123 更新时间:2023-12-02 14:28:29 25 4
gpt4 key购买 nike

我正在尝试一个输出到控制台的简单程序。一切正常,只是意外地未定义,我不知道为什么会得到它。任何人请解释一下出了什么问题以及如何使我的代码更好。谢谢

var next = document.getElementById('next');

var questions =
[

{
question: "Color of sky is ?",
choices: ["Green","White", "Blue", "Red"],
answer: 2
},
{
question: "Color of milk is ?",
choices: ["Green","White", "Blue", "Red"],
answer: 1
},
{
question: "Color of Grass is ?",
choices: ["Green","White", "Blue", "Red"],
answer: 0
}

];

var counter = 0;


function loadQuestion () {

var obj = questions[counter];
var quest = obj.question;
var choice = obj.choices;
function options() {
choice.forEach(function(val){

console.log(val);
return false;
});
}
var answer = obj.answer;

counter++;

console.log ( " Question : " + quest );
console.log( options() );
console.log( answer );
}

next.onclick = function() {
if ( counter < questions.length ) {
loadQuestion();
}
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>

<div id="quiz-container">
<button id="next"> Next Question </button>
</div>

</body>
</html>

最佳答案

你为什么这样做:

console.log( options() );

options 函数中,您已经打印了选项,因此您应该仅将此行替换为:

options();

并且如果您想知道为什么它的 print undefined 因为 options 函数不返回任何内容(return false 只是每个项目的 forEach 回调的返回),如果您这样做下面它将打印 true 而不是 undefined:

function options() {
choice.forEach(function(val){

console.log(val);
return false;
});
return true;
}

示例:

function a(){}
console.log( a() ); //undefined

function a(){return 1;}
console.log( a() ); // 1

关于javascript - 我在 JavaScript 中遇到了未定义的问题,并且不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38038916/

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