“+”在我的函数中表现异常

"+" behaving strangely in my functions

我正在制作一个数学应用程序。 在那里,我希望能够通过随机运算生成数学任务。

var generator = {

    operations: [
        "+",
        "-",
        "*",
        "/"
    ],

    randomOperation: function(amount) {
        if (amount == 2) {
            return this.operations[Math.round(Math.random())];
        }
        if (amount == 4) {
            return this.operations[Math.floor(Math.random() * 4)];
        }
    },

    addOperand: function(operand, maxSize, minSize) {
        var op = operand;
        console.log('op ' + op);
        if (operand == 2||4) {
            console.log('getting random operand');
            op = this.randomOperation(operand);
        }
        var number = this.randomNumber(maxSize, minSize);
        console.log('number ' + number);

        this.tasks.push({
            value: number,
            operation: op
        });
        console.log('added ' + op + ' ' + number);
    }
    // other stuff
}

所以我希望能够使用不同的参数调用该方法: '+',如果我绝对希望它是 + '-',如果我想要一个 - 等等 如果我传递一个数字(2 或 4),它应该从 2 (+-) 或 4 (+-*/)

中随机生成

但确实发生了一些奇怪的事情...

控制台输出为:

op +
getting random operand
number 2
added undefined 2

为什么“+”被认为是 2||4? 它显然以“+”的形式出现,但随后以某种方式...传递给 randomOperation(),当然,returns 什么都没有。

谢谢

PS:有没有一种方法可以在此处粘贴代码而无需手动更正所有缩进?这真的很烦人:(

表达式 operand == 2 || 4 被解析为 (operand == 2) || 4

如果 operand == 2 则为 true,否则为 4

两种可能的结果都是 "truthy",因此无论 operand

的值如何,总是采用 if 分支

如果您希望仅当操作数为 2 或 4 时才采用分支,则需要:

(operand == 2 || operand == 4)

这个:

if (operand == 2||4) {

并不意味着 "if operand == 2, or operand == 4" -- 它意味着“如果操作数 == 2,则 true,否则 4.

您想说:

if ((operand == 2) || (operand == 4)) {

这不是您检查值是一个值还是另一个值的方法。该代码正在做的是

if ( (operand==2) || 4 )

所以 id 操作数为 2 为真,否则为 returns 4 为真值。所以基本上它永远是真的。

检查需要

if( operand == 2|| operand == 4)

或者你可以使用模数

if (operand %2 === 0) 

或indexOf

if ([2,4].indexOf(operand)>-1)