admin管理员组文章数量:1333710
For the life of me I don't understand why this doesn't work. It looks similar if not identical to many solutions i've seen. Clearly there is something i'm missing. If anyone would care to explain id appreciate it.
var isEven = function(number) {
if (isEven % 2 === 0) {
return true;
} else {
return false;
}
};
For the life of me I don't understand why this doesn't work. It looks similar if not identical to many solutions i've seen. Clearly there is something i'm missing. If anyone would care to explain id appreciate it.
var isEven = function(number) {
if (isEven % 2 === 0) {
return true;
} else {
return false;
}
};
Share Improve this question asked Mar 4, 2016 at 1:28 Dane ChristianDane Christian 92 silver badges4 bronze badges 3- 4 Inside your function you should use number, not isEven. – visola Commented Mar 4, 2016 at 1:30
- thank you, that makes a lot of sense.. fixed – Dane Christian Commented Mar 4, 2016 at 1:42
-
I suggest you learn how to debug your programs. For instance, in the first line of the function, you could output
isEven % 2
to see what its value is. You couldalert
it, orconsole.log
it. Or you could put a breakpoint there and examine the value ofisEven % 2
in the debugger. In either case, you would see the value wasNaN
. To figure out why, you could then examine the value ofisEven
itself, and see that it was a function. That would point you to the problem that you are taking the modulus of the function, rather than the parameternumber
. – user663031 Commented Mar 4, 2016 at 3:28
2 Answers
Reset to default 9You can fix it and shorten it to this:
function isEven(number) {
return number % 2 === 0;
}
No need for the if/else
. You can just directly return the result of the parison.
Your isEven function has a value that is a function.
Therefore, when you check inside (isEven % 2 === 0)
it ends up always being false because isEven is NaN.
Which will always return false.
Instead, using your parameter number
is the correct solution.
var isEven = function(number) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
}
本文标签: if statementchecking if number is even in JavaScriptStack Overflow
版权声明:本文标题:if statement - checking if number is even in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742354869a2459206.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论