gpt4 book ai didi

jquery在函数之间传递var而不使用全局var或var外部函数

转载 作者:行者123 更新时间:2023-12-01 07:42:03 25 4
gpt4 key购买 nike

我需要将 currentQuest.options 传递给 showResult 函数,而不声明全局 var 或这些函数之外的 var。

这可能吗?我读过其他类似的问题,但所有正确的答案都使用全局变量。

var pool = {
q1: {
question: "This is question number 1",
options: ["Option 1", "Option 2", "Option 3", "Option 4"],
answer: 0, //answer uses property option key
used: false
},
q2: {
/*...*/
},
/*...just more q here...*/
}

//choose a random question
function randomQuest(obj) {
var keys = Object.keys(obj);
return obj[keys[keys.length * Math.random() << 0]];
}

//show question and options
function showQuest() {
var currentQuest = randomQuest(pool);
$(".answer").html(""); //clear old answer
$(".question").html(currentQuest.question);
$(".options").html(currentQuest.options);
currentQuest.used = true; //mark question used

console.log(currentQuest.question);
console.log("used? ", currentQuest.used);
}

function showResult() {
$(".question").html("");
$(".options").html("");
var x = currentQuest.answer;
$(".answer").html("Here is the answer " + currentQuest.options[x]); //how to pass currentQuest here?
}

function timer() {
var seconds = 4;
var interval = setInterval(function() {
seconds--;
$(".timer").html("<p>Time remaining: " + seconds + " s</p>");
if (seconds == 0) {
clearInterval(interval);
showResult();
}
}, 1000);
}

//when click start game
$(".btn").on("click", function() {
timer();
showQuest();
});

逻辑是:当单击按钮时 -> 启动计时器,显示第一个问题(从池中随机选择)当计时器达到 0 时,显示结果,等待几秒钟,重置计时器,显示另一个问题,再次启动计时器。

最佳答案

您可以使用函数参数来实现此目的。

function showQuest(currentQuest) {
$(".answer").html(""); //clear old answer
$(".question").html(currentQuest.question);
$(".options").html(currentQuest.options);
currentQuest.used = true; //mark question used

console.log(currentQuest.question);
console.log("used? ", currentQuest.used);
}

function showResult(currentQuest) {
$(".question").html("");
$(".options").html("");
var x = currentQuest.answer;
$(".answer").html("Here is the answer " + currentQuest.options[x]); //how to pass currentQuest here?
}

function timer(currentQuest) {
var seconds = 4;
var interval = setInterval(function() {
seconds--;
$(".timer").html("<p>Time remaining: " + seconds + " s</p>");
if (seconds == 0) {
clearInterval(interval);
showResult(currentQuest);
}
}, 1000);
}

//when click start game
$(".btn").on("click", function() {
var currentQuest = randomQuest(pool);
timer(currentQuest);
showQuest(currentQuest);
});

编辑:请尝试此方法来获取随机索引。

// From MDN
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}

function randomQuest(obj) {
var keys = Object.keys(obj);
return obj[keys[getRandomInt(0, keys.length)]];
}

关于jquery在函数之间传递var而不使用全局var或var外部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45951656/

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