[英]How do I write an if/else statement inside a function that tells me if a number is evenly divisible by 2 (in javascript)
I'm working through codacademy and I can't understand the help discussions in the forum. 我正在通过codacademy工作,但我听不懂论坛中的帮助讨论。
This is what I have so far but it returns false when i run the function with an even number: 到目前为止,这是我所拥有的,但是当我使用偶数运行函数时,它返回false:
var isEven = function(number) {
if (isEven % 2 == 0){
return true;
}else{
return false;
}
};
You are performing the mathematical operation on isEven
(the function itself). 您正在对
isEven
(函数本身)执行数学运算。 You need to check number
: 您需要检查
number
:
var isEven = function(number) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
};
or better yet: 或更好:
var isEven = function(number) {
return number % 2 === 0;
};
You could even do this, by making use of the truthy/falsy behavior of 1
and 0
: 您甚至可以通过利用
1
和0
的真实/虚假行为来做到这一点:
var isEven = function(number) {
return !(number % 2);
};
but I think the previous approach more clearly conveys how the logic works. 但是我认为以前的方法更清楚地传达了逻辑的工作原理。
you can write this function as follows: 您可以如下编写此函数:
var isEven = function(number) {
return ((number % 2) == 0);
}
Your function is not working because you're checking against the function name, not the function parameter (number). 您的函数无法正常运行,因为您要检查的是函数名称,而不是函数参数(数字)。 Try this:
尝试这个:
var isEven = function(number) {
return number % 2 == 0;
}
You doing it wrong in isEven
itself.. Do it like.. 您在
isEven
本身中做错了。
var isEven = function(number) {
return number% 2 == 0;
}
Consider the following: 考虑以下:
0
is considered to be false
in Javascript. 0
被认为是false
的。 1
is considered to be true
in Javascript. 1
在Javascript中被认为是true
的。 !
makes false
become true
and vice versa. false
变为true
,反之亦然。 %
operator can be used to keep higher numbers in a zero-to-one range. %
运算符可用于将较高的数字保持在零到一的范围内。 Since 0 % 2
gives 0
(ie false
) and 1 % 2
gives 1
(ie true
), you simply need to invert the result with !
由于
0 % 2
给出0
(即false
),而1 % 2
给出1
(即true
),因此您只需要使用!
求反!
: :
function isEven(x) { return !(x % 2); }
console.log(isEven(0)); // true
console.log(isEven(1)); // false
console.log(isEven(2)); // true
console.log(isEven(3)); // false
Note that this could also be written as: 请注意,这也可以写成:
function isEven(x) { return (x % 2) == 0; }
...because: ...因为:
0 % 2
is 0
(so it is true
to say that it is equal to zero). 0 % 2
是0
(因此它是true
地说,它是等于零)。 1 % 2
is 1
(so it is false
to say that it is equal to zero). 1 % 2
为1
(因此说它等于零是false
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.