gpt4 book ai didi

javascript - 构建简单的 JavaScript 测验时遇到问题

转载 作者:行者123 更新时间:2023-11-28 20:21:36 26 4
gpt4 key购买 nike

伙计们!

我正在尝试使用 JavaScript 构建一个基本的测验应用程序,但遇到了一些“障碍”

为什么我的代码不将 allQuestions 数组的元素存储在 currentQuestion 变量中?

这是代码:

var allQuestions = [
{question: 'What is the first letter of the alphabet?',
choices: ['a', 'b', 'c', 'd'],
correctAnswer: 0
},
{
question: 'What is the second letter of the alphabet?',
choices: ['a', 'b', 'c', 'd'],
correctAnswer: 1
},
{
question: 'What is the third letter of the alphabet?',
choices: ['a', 'b', 'c', 'd'],
correctAnswer: 2
},
{
question: 'What is the last letter of the alphabet?',
choices: ['a', 'b', 'c', 'z'],
correctAnswer: 3
}];

var currentQuestion = {};

function pickRandomQuestion(arr) {
return this[Math.floor(Math.random() * this.length)];
}

currentQuestion = pickRandomQuestion(allQuestions);

谢谢!

最佳答案

您正在查询this,这将是父上下文 - 可能是一个窗口,因为我看不到父函数。您需要改为查找 arr:

function pickRandomQuestion(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}

关于javascript - 构建简单的 JavaScript 测验时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18203025/

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