gpt4 book ai didi

javascript - 测试一个值是奇数还是偶数

转载 作者:IT老高 更新时间:2023-10-28 13:18:15 26 4
gpt4 key购买 nike

我决定用一个非常简单的算法创建简单的 isEvenisOdd 函数:

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 的最终版本。

最佳答案

使用模数:

function isEven(n) {
return n % 2 == 0;
}

function isOdd(n) {
return Math.abs(n % 2) == 1;
}

您可以检查 Javascript 中的任何值是否可以强制转换为数字:

Number.isFinite(parseFloat(n))

最好在 isEvenisOdd 函数之外进行此检查,因此您不必在两个函数中重复错误处理。

关于javascript - 测试一个值是奇数还是偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6211613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com