防止 isNaN 隐式转换为数字

Prevent isNaN implicit conversion to number

我正在学习一些 JavaScript 和 运行 的怪癖,想知道是否有人知道覆盖此行为的方法。我希望能够测试传递给函数的值是否是 真实 数字,我认为使用 === 进行 isNaN() 检查需要关心那个,但事实并非如此。

示例函数:

var foodDemand = function(food) {
    if <b><i>(isNaN(food) === false)</I></b> {
        console.log("I can't eat " + food + " because it's a number");
    } else {
        console.log("I want to eat " + food);
    }
};
</pre>

我用这个测试:

// behaves as expected
foodDemand("steak");
foodDemand(999999999);
foodDemand(0.0000001337);
foodDemand([1]);
foodDemand(undefined);
foodDemand(NaN);
foodDemand({});
// converts non-number to a number
foodDemand("42");
foodDemand("");
foodDemand(null);
foodDemand([]);
foodDemand("\n");</pre>

输出(斜体表示意外结果)

I want to eat steak
I can't eat 999999999 because it's a number
I can't eat 1.337e-7 because it's a number
I can't eat 1 because it's a number
I want to eat undefined
I want to eat NaN
I want to eat [object Object]
<i>I can't eat 42 because it's a number
I can't eat  because it's a number
I can't eat null because it's a number
I can't eat  because it's a number
I can't eat 
 because it's a number</i>

有没有办法让isNaN()更严格?

isNaN() 不检查某物是否不是数字类型,它从字面上检查某物是否为值 "NaN",如您所见。 typeof 是你的朋友。

((typeof foo) === 'number') && !isNaN(foo) 应该可以满足您的需求。

isNaN函数的目的是检查一个值是否正好等于内置的NaN常量值。它不应该用于检查某物是否为数字,即使这看起来有悖常理。它存在的唯一原因是 NaN === NaN returns false,所以它是检查涉及数字的函数是否失败的唯一方法。

试试这个:

if (typeof food == "number") {
    console.log("I can't eat " + food + " because it's a number");
} else {
    console.log("I want to eat " + food);
}

isNaN 的目的不是真正地测试某物是否真的不是数字,而是测试某物是否为 NaN(因为 NaN===NaN returns false in JavaScript 你不能使用相等)。

你应该用typeof代替,然后是NaN:

if((typeof food)==="number" && !isNaN(food))

为什么,你可能会问,NaN 不等于 NaN 吗??这又是 JavaScript 臭名昭著的怪癖之一吗?

事实证明,这种行为是有充分理由的。不能 return 一个真实结果的数学运算,即使是无穷大,也不会抱怨并抛出错误。他们只是 return NaN。例如,0/0、sqrt(-1)、acos(2)。拥有 Math.sqrt(-1) === 0/0 会不会很奇怪?所以 NaN 甚至不等于它自己。因此,如果您真的想检查值 是否为 NaN.

,则需要像 isNaN 这样的原语