下载安卓APP箭头
箭头给我发消息

客服QQ:3315713922

web前端:JS中判断null、undefined与NaN的方法

作者:幂次方     来源: https://www.cnblogs.com/lzghyh/p/11871386.html点击数:1804发布时间: 2020-03-13 10:09:04

标签: JScriptJSnull

Web开发

  Javascript一种直译式脚本语言,是一种动态类型、弱类型、基于原型的语言,内置支持类型。它的解释器被称为JavaScript引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在html(标准通用标记语言下的一个应用)网页上使用,用来给HTML网页增加动态功能。

  1.判断undefined:

  vartmp=undefined;

  if(typeof(tmp)=="undefined"){

  console.log("undefined");

  }

  说明:typeof返回的是字符串,有六种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined"

  2.判断null:

  vartmp=null;

  if(!tmp&&typeof(tmp)!="undefined"&&tmp!=0){

  console.log("null");

  }

  3.判断NaN:

  vartmp=0/0;

  if(isNaN(tmp)){

  console.log("NaN");

  }

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

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

  4.判断undefined和null的关系:

  vartmp=undefined;

  if(tmp==undefined){

  console.log("undefined==undefined");

  }

  vartmp=undefined;

  if(tmp==null){

  console.log("null==undefined");

  }

  结论:null==undefined

  5.判断undefined、null与NaN:

  vartmp=null;

  vartmp1=undefined;

  vartmp2=NaN;

  if(!tmp){

  console.log("nullorundefinedorNaN");

  }

  if(!tmp1){

  console.log("nullorundefinedorNaN");

  }

  if(!tmp2){

  console.log("nullorundefinedorNaN");

  }

  结果:都打印

  为了取得技术优势,微软推出了JScript,CEnvi推出ScriptEase,与JavaScript同样可在浏览器上运行。为了统一规格,因为JavaScript兼容于ECMA标准,因此也称为ECMAScript。

赞(12)
踩(0)
分享到:
华为认证网络工程师 HCIE直播课视频教程