与window.isFinite
,您必须意识到强制类型window.isNaN
时遇到的问题。
window.IsNaN 摘要
确定一个值是否为 NaN。小心,这个功能坏了。你可能对 ECMAScript 6 Number.isNaN 感兴趣。
例子
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
isNaN(true); // false
isNaN(null); // false
isNaN(37); // false
// strings
isNaN("37"); // false: "37" is converted to the number 37 which is not NaN
isNaN("37.37"); // false: "37.37" is converted to the number 37.37 which is not NaN
isNaN(""); // false: the empty string is converted to 0 which is not NaN
isNaN(" "); // false: a string with spaces is converted to 0 which is not NaN
// This is a false positive and the reason why isNaN is not entirely reliable
isNaN("blabla") // true: "blabla" is converted to a number. Parsing this as a number fails and returns NaN
在 ECMAScript 6 中,有一些新方法Number.isNaN
可以Number.isFinite
解决这些问题。(当然这些在许多浏览器中都不可用)
Number.isFinite
相当于
function isFinite(number) {
return typeof number === "number" && window.isFinite(number);
}
因此,作为一种解决方案,您需要考虑这样的事情(跨浏览器)。
注意:此解决方案仍允许您输入十六进制或科学记数法“0xA”、“1e10”
Javascript
function isFinite(number) {
return typeof number === "number" && window.isFinite(number);
}
function trim(string) {
return string.replace(/^\s+|\s+$/g, "");
}
var price = document.getElementById("price");
price.onchange = function (e) {
var evt = e || window.event,
target = evt.target || evt.srcElement,
value = trim(target.value) || "NaN",
number = +value;
console.log("number:", number);
console.log("isFinite:", isFinite(number));
}
在jsfiddle 上