我正在制作一个数学应用程序。 在那里,我希望能够通过随机运算生成数学任务。
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(),当然,它什么也不返回。
谢谢
PS:有没有一种方法可以将代码粘贴到此处,而无需手动更正所有缩进?这真的很烦人:(
最佳答案
表达式操作数 == 2 || 4
被解析为 (operand == 2) || 4
.
如果operand == 2
,则为true
,否则为4
。
两种可能的结果都是“真实的”,因此无论操作数
的值如何,总是采用if
分支
如果您希望仅在操作数为 2 或 4 时才采用分支,则需要:
(operand == 2 || operand == 4)
关于javascript - "+"在我的函数中表现奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33926522/