"+"在我的功能中表现得很奇怪

use*_*706 0 javascript operators

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

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
}
Run Code Online (Sandbox Code Playgroud)

所以我希望能够用不同的参数调用方法:'+',如果我肯定希望它是+' - ',如果我想要一个 - 依此类推,如果我传递一个数字(2或4),它应该从2(+ - )或4(+ - */)中随机生成

但是真的很奇怪......

控制台输出是:

op +
getting random operand
number 2
added undefined 2
Run Code Online (Sandbox Code Playgroud)

为什么'+'被认为是2 || 4?它显然是以'+'形式出现,但后来以某种方式...传递给randomOperation(),当然,它什么都不返回.

谢谢

PS:有没有办法在这里粘贴代码而不用手动纠正所有缩进的痛苦?这真烦人:(

Aln*_*tak 5

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

这将是true如果operand == 2,或4以其他方式.

两种可能的结果都是"真实的",因此if无论价值如何,都会始终采用分支operand

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

(operand == 2 || operand == 4)
Run Code Online (Sandbox Code Playgroud)