zoukankan      html  css  js  c++  java
  • JS中如何判断null、undefined与NaN

    http://www.phpernote.com/javascript-function/900.html

    javascript中如何判断一个变量是否是null,undefined还是NaN呢?下面我们看看具体的判断方法吧。

    主要是通过 typeof 这个方法去判断,typeof 返回的是字符串,有六种可能的结果:"number"、"string"、"boolean"、"object"、"function"、"undefined"。

    为什么用typeof,判定有没有声明。

    if(Upcallback === 'undefined')会报错的。
    if(typeof Upcallback === 'undefined'){Upcallback = function(){};}


    有时必须使用typeof的原因是,如果一个变量根本没有被声明,只有使用typeof判断才不会报错,用相等运算符判断会抛出异常.

    // x没有被声明过
    if (typeof x === 'undefined') { // 不会报错
       // these statements execute
    }
    
    if(x === undefined){ // 抛出ReferenceError异常
    
    }


    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/undefined

    1.判断undefined:

    1 var tmp=undefined;
    2 if(typeof(tmp)=="undefined"){
    3     alert("undefined");
    4 }

    2.判断null:

    1 var tmp=null;
    2 if(!tmp&&typeof(tmp)!="undefined"&&tmp!=0){
    3     alert("null");
    4 }

    3.判断NaN:

    1 var tmp=0/0;//www.phpernote.com
    2 if(isNaN(tmp)){
    3     alert("NaN");
    4 }

    说明:如果把 NaN 与任何值(包括其自身)相比得到的结果均是 false,所以要判断某个值是否是 NaN,不能使用==或 === 运算符。

    提示:isNaN() 函数通常用于检测 parseFloat() 和 parseInt() 的结果,以判断它们表示的是否是合法的数字。当然也可以用 isNaN() 函数来检测算数错误,比如用 0 作除数的情况。

    4.判断undefined和null:

    1 var tmp=undefined;
    2 if(tmp==undefined){
    3     alert("null or undefined");
    4 }

    或者:

    1 var tmp=undefined;
    2 if(tmp==null){
    3     alert("null or undefined");
    4 }

    说明:null==undefined

    5.判断undefined、null与NaN:

    1 var tmp=null;
    2 if(!tmp){
    3     alert("null or undefined or NaN");
    4 }

    提示:一般不那么区分就使用这个足够。

  • 相关阅读:
    随机小错2_0527
    随计小错
    C++实现读写文件
    03-树2 List Leaves (25 分)
    获取毫秒级的时间戳
    new对象时,类名后加括号与不加括号的区别
    FoxMail 7.2的邮件存储目录修改
    C/C++ 开源算法库
    VS2015的安装
    脏内存导致BUG的问题
  • 原文地址:https://www.cnblogs.com/darr/p/4932323.html
Copyright © 2011-2022 走看看