题
如何找出如果一个变量被2整除?此外,我需要做的一个函数,如果它是,做不同的功能,如果它不是
解决方案
使用模量:
// Will evaluate to true if the variable is divisible by 2
variable % 2 === 0
其他提示
严重的是,有没有jQuery插件奇/偶校验?
那么,不再 - 释放“炉” MIT许可下一个jQuery插件来测试,如果一个给定的数目为奇数/偶数。
源代码也可在 http://jsfiddle.net/7HQNG/
试验套件可在 http://jsfiddle.net/zeuRV/
(function() {
/*
* isEven(n)
* @args number n
* @return boolean returns whether the given number is even
*/
jQuery.isEven = function(number) {
return number % 2 == 0;
};
/* isOdd(n)
* @args number n
* @return boolean returns whether the given number is odd
*/
jQuery.isOdd = function(number) {
return !jQuery.isEven(number);
};
})();
您不需要jQuery的。只需使用 JavaScript的模操作。
可以使用模数运算符这样的,没有必要的jQuery。只需用代码替换alerts
。
var x = 2;
if (x % 2 == 0)
{
alert('even');
}
else
{
alert('odd')
}
您可以做一个更好的方式(高达50%,快于模运算符):
奇:X&1 甚至:(X 1)
参考:高性能的JavaScript,8. - >位运算符
您还可以:
if (x & 1)
itsOdd();
else
itsEven();
var x = 2;
x % 2 ? oddFunction() : evenFunction();
if (x & 1)
itIsOddNumber();
else
itIsEvenNumber();
请填写下面的代码在控制台:
var isEven = function(deep) {
if (deep % 2 === 0) {
return true;
}
else {
return false;
}
};
isEven(44);
请注意:这将返回true,如果输入的号码甚至否则为false
使用模量,但..上述接受的答案是略微不准确的。我相信,因为x是在JavaScript数字类型,操作者应该是双重分配,而不是一个三重分配,像这样:
x % 2 == 0
记住要过声明变量,所以很明显该行无法写入独立。 :-)通常用作if
声明。希望这有助于。
希望这有助于。
let number = 7;
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
下面是将登录到控制台的输入的奇偶性的完整功能。
const checkNumber = (x) => {
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
}
阵列= [1,2,3,4,5,6,7,8,9,10]
array.each {| X |将X个如果x%2 == 0}
红宝石:d
2 4 6 8 10
不隶属于 StackOverflow