测试一个值是奇数还是偶数
我决定使用非常简单的算法创建简单的 isEven 和 isOdd 函数:
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
如果 n 具有某些参数,则可以,但在许多情况下会失败。因此,我开始创建强大的函数,为尽可能多的场景提供正确的结果,以便仅测试 JavaScript 数字限制内的整数,其他所有内容都返回 false(包括 + 和 - 无穷大)。请注意,零是偶数。
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
有人能看出上述内容有什么问题吗?是否有更好的(即更准确、更快或更简洁而不混淆)版本?
有各种与其他语言相关的帖子,但我似乎找不到 ECMAScript 的明确版本。
I decided to create simple isEven and isOdd function with a very simple algorithm:
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
使用模数:
您可以检查 Javascript 中的任何值是否可以强制转换为数字:
此检查最好在
isEven
和isOdd
函数之外完成,这样您就不会'不必在两个函数中重复错误处理。Use modulus:
You can check that any value in Javascript can be coerced to a number with:
This check should preferably be done outside the
isEven
andisOdd
functions, so you don't have to duplicate error handling in both functions.我更喜欢使用位测试:
这测试第一位是否表示奇数。
I prefer using a bit test:
This tests whether the first bit is on which signifies an odd number.
下面的怎么样?我只在 IE 中测试了这个,但它很乐意处理表示任何长度的数字、整数或浮点数的实际数字的字符串,并且当传递布尔值、未定义、null、数组或对象时,两个函数都返回 false。 (由您决定是否要在传入字符串时忽略前导空格或尾随空格 - 我假设它们不会被忽略并导致两个函数都返回 false。)
How about the following? I only tested this in IE, but it was quite happy to handle strings representing numbers of any length, actual numbers that were integers or floats, and both functions returned false when passed a boolean, undefined, null, an array or an object. (Up to you whether you want to ignore leading or trailing blanks when a string is passed in - I've assumed they are not ignored and cause both functions to return false.)
注意:也有负数。
其中
Note: there are also negative numbers.
where
完成罗伯特·布里西塔的位测试。
To complete Robert Brisita's bit test .
为什么不这样做:
Why not just do this:
几个
A few
我们只需要一行代码即可!
这是一种更新的替代方法,使用新的 ES6 语法,以及 单行语法 用于
if -else
语句调用:We just need one line of code for this!
Here a newer and alternative way to do this, using the new ES6 syntax for JS functions, and the one-line syntax for the
if-else
statement call:对史蒂夫·梅恩答案的简单修改/改进!
注意:如果无效则返回false!
A simple modification/improvement of Steve Mayne answer!
Note: Returns false if invalid!
罗伯特·布里西塔的回答非常棒!但是,我希望该解决方案成为 JS
Number
原型的一部分,以便可以在任何数字变量上调用它,而不是将变量传递到函数中。此外,我想要一个能够为浮点数返回 null 的解决方案,因为它们不应被视为偶数或奇数。请参阅下面的我的原型解决方案:您现在可以对任何数值变量调用这些方法。请参阅下面的一些测试:
The answer from Robert Brisita is great! However, I wanted the solution to be part of the JS
Number
prototype so that it could be called on any numeric variable rather than passing the variable into a function. Furthermore, I wanted a solution that would returnnull
for floats as they should be considered neither even nor odd. See below for my prototype solution:You can now call these methods on any numeric variable. See below for a few tests: