Phr*_*cis 3 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");
输出(斜体表示意外结果):
Run Code Online (Sandbox Code Playgroud)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()更严格?
isNaN的目的不是测试某些东西是不是数字,而是测试某些东西是否为数字NaN(因为NaN===NaN在JavaScript中返回false,你不能使用相等).
你应该使用typeof,然后是isNaN:
if((typeof food)==="number" && !isNaN(food))
Run Code Online (Sandbox Code Playgroud)
你可能会问,为什么NaN不等于NaN?这是JavaScript的臭名昭着的怪癖吗?
事实证明这种行为是有充分理由的.无法返回实际结果的数学运算,即使是无限,也不会抱怨并抛出错误.他们只是回归NaN.例如,0/0,sqrt(-1),acos(2).拥有不是很奇怪Math.sqrt(-1) === 0/0吗?所以NaN甚至不等于自己.因此,isNaN如果您确实想要检查值是否为NaN,则需要原语.