根据条件将函数放入数组中(如果选中复选框)

Putting functions in an array based on a condition (if checkbox is checked)

本文关键字:如果 复选框 数组 条件 函数      更新时间:2023-09-26

我还在玩数学游戏。它现在生成随机的加法、减法、乘法和除法问题。我所做的是为每种类型的数学运算创建函数,并将其放入一个数组中,然后我有另一个函数从该数组中获得一个随机函数。它起作用了!(如果问题没有出现,请单击"返回选项"按钮,然后再次单击"点击播放"按钮)点击此处查看。

//function definitions (See line 116 of jsFiddle link)
var operatorFunctions = [additionQuest,
           subtractionQuest,
           multiplicationQuest,
           divisionQuest];
//Array randomizer
function randomFrom(array) {return array[Math.floor(Math.random() * array.length)];}
function randomOp() {
    var func = randomFrom(operatorFunctions);
    (func)();
}

但现在我想让用户根据他们在开始屏幕上选择的内容,选择他们想练习的问题(操作员)。我的想法是,如果复选框被选中,那么它对应的函数将被推送到operatorFunctions数组中。

var operatorFunctions = []
// Code below is wrapped in a function that is executed on start button click
if ($('#allowAddition').is(':checked')) {
allowAdd = true;
} else {
allowAdd = false;
}
if (allowAdd == true) {
    operatorFunctions.push(additionQuest);
    return operatorFunctions;
}

但这根本不起作用!你们看到我的逻辑有什么明显的缺陷吗?我觉得这是一个范围的事情。。。?

此外,我的divisionQuest函数不是100%正确的,有时第一个问题没有初始化。此外,我似乎在不该回答的时候反复遇到同样的问题。(在第49行的第一个jsFiddle上注释数组外的其他运算符函数,以查看这些问题。)你们看到这个函数有什么问题吗?

function divisionQuest() {
    var self = this;
var $numberOne = getRandomInt(0,rangeMax);
var $numberTwo = getRandomInt(1,rangeMax); //Divisor cannot be zero
 //This makes sure the a function produces a question whose answer is a whole number
while ($numberOne % $numberTwo != 0) {
    $numberOne = getRandomInt(0,rangeMax);
    $numberTwo = getRandomInt(1,rangeMax)
    return $numberOne, $numberTwo;
}
self.quest = $numberOne / $numberTwo;
self.formatquest = $numberOne + " ÷ " + $numberTwo; //Tidy it up a bit
$questionHolder.html(self.formatquest);
$questionHolder.hide().fadeIn(600);
}

试试这个:http://jsfiddle.net/rezashamdani/nz2cqja8/

<input type="checkbox" name="chooseOp" id="allowAddition" value="+" />Addition中的id错误和通知行:43,65-97