JavaScript If Else 带返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22080271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript If Else with Return
提问by danteMingione
Still doing the Codecademy training for JavaScript and I've hit a road block.
仍在为 JavaScript 进行 Codecademy 培训,但我遇到了障碍。
Here's the code:
这是代码:
var isEven = function(number) {
if (isEven % 2 === 0) {
return true;
} else {
return false;
}
};
isEven(2);
So I'm referencing the variable "isEven." Then, I'm telling it to check the number and cross-check it with the modulo to check the remainder against 2 to find out if it's even. If it is, for example, 2 like in the example it should return a remainder of zero, therefore the if is true and it returns true. But it returns false every time. There's no warning messages in the code but when I hit save and it checks it it gives me this message:
所以我引用了变量“isEven”。然后,我告诉它检查数字并用模数交叉检查它以检查余数与 2 的关系,以确定它是否为偶数。如果它是,例如,像示例中的 2,它应该返回零的余数,因此 if 为真,它返回真。但是每次都返回false。代码中没有警告消息,但是当我点击保存并检查它时,它给了我这条消息:
"Oops, try again. Looks like your function returns false when number = 2. Check whether your code inside the if/else statement correctly returns true if the number it receives is even."
“糟糕,再试一次。看起来你的函数在 number = 2 时返回 false。如果它收到的数字是偶数,请检查 if/else 语句中的代码是否正确返回 true。”
回答by Popo
I think you had the wrong variable name:
我认为你有错误的变量名:
var isEven = function(number) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
};
isEven(2);
回答by GetSwifty
you could also do:
你也可以这样做:
var isEven = function(number) {
return number % 2 === 0
};
回答by Igor ??eki?
Your function and variable have the same name. Name the function or the variable differently and it will work.
您的函数和变量具有相同的名称。以不同的方式命名函数或变量,它将起作用。
回答by andrey.rtv
You need change varible isEven to number, like:
您需要将变量 isEven 更改为数字,例如:
var isEven = function(number) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
};
isEven(2);