您的位置:首页 > Web前端 > JavaScript

用isNaN函数判断是否是Number中的坑

2016-06-28 09:17 417 查看


isNaN主要作用是判断是否是NaN,反过来却不一定是Number,类型转换成Number的值也会返回false


ExamplesEDIT

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("123ABC");  // true:  parseInt("123ABC") is 123 but Number("123ABC") is 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

// dates
isNaN(new Date());                // false
isNaN(new Date().toString());     // true

// 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript