防止isNaN隐式转换为数字

时间:2015-04-15 19:13:40

标签: javascript validation numbers

我正在学习一些JavaScript并遇到了一个怪癖,并想知道是否有人知道如何覆盖这种行为。我希望能够测试传递给函数的值是否是真实的号码,并且我认为使用===进行isNaN()检查可以解决这个问题,但事实并非如此。

示例功能:

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

我测试了这个:

// 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");

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

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 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

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

4 个答案:

答案 0 :(得分:6)

isNaN的目的不是测试某些东西是不是数字,而是测试某些东西是否为数字NaN(因为NaN===NaN在JavaScript中返回false,你可以&# 39;使用平等)。

您应该使用typeof,然后使用isNaN:

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

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

原来这种行为是有充分理由的。无法返回真实结果的数学运算,即使是无限,也不会抱怨并抛出错误。他们只是回归NaN。例如,0/0,sqrt(-1),acos(2)。拥有Math.sqrt(-1) === 0/0会不会很奇怪?所以NaN甚至不等于自己。因此,如果您确实想要检查值是否为NaN ,则需要isNaN这样的原语。

答案 1 :(得分:4)

isNaN()没有检查某些东西是不是数字类型,它确实检查某些东西是否为“NaN”,正如您所发现的那样。 typeof是你的朋友。

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

答案 2 :(得分:1)

isNaN函数的目的是检查值是否与内置NaN常量值完全相等。它不应该被用来检查某些东西是否是一个数字,即使这似乎是违反直觉的。它只是因为NaN === NaN返回false而存在,因此它是检查涉及数字的函数是否失败的唯一方法。

答案 3 :(得分:1)

试试这个:

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