首页 > 原生的js如何判断值为NaN,undefined(在不使用isNaN之类的全局函数情况下)

原生的js如何判断值为NaN,undefined(在不使用isNaN之类的全局函数情况下)

如题,不使用js自带的函数的前提下实现


function checkNaN(obj) {
    return obj !== obj
}

function checkUndefined(obj, notDefined) {
    return obj === notDefined
}

typeof a === 'undfined'
// check nan
var n = 1/'xs1212';

function checkNaN(num) { 
    return (type of num === 'number') && !(num >= 0 || num < 0); 
}
checkNan(n); // true

Number.NaN 其实是Number的一个特殊值而已,即非数字(not a number),那么也就是说 typeof(NaN)值是 "number",所以:

var isNaN2 = function(val){
    return typeof NaN === 'number' && val !== val;
}

undefined 是js里其中一个特殊的基本类型, typeof(undefined)值是 "undefined"

var isUndefined = function(val){
 return val === undefined; // or typeof val === 'undefined'
}
【热门文章】
【热门文章】