js 判断数据类型,以及undefined和null的理解

时间:2020-12-30 23:59:03   收藏:0   阅读:77

变量声明和赋值的几种状态


数据类型的分类


typeof和数据类型


未声明和未赋值状态下的undefined值

var message;      // 这个变量声明后默认取得 undefined 值
// 下面这个变量没有声明
// var age;
alert(message);      // "undefined"
alert(age);          // 产生错误

小结: 对于未声明的变量执行alert会报错(因为对于未声明的变量,只能执行typeof检测数据类型这一项操作。当然delete也行,但没有意义,而且严格模式也报错)


var message;      // 这个变量声明后默认取得 undefined 值
// 下面这个变量没有声明
// var age;
alert(typeof message);      // "undefined"
alert(typeof age);          // "undefined"

小结: 对于未声明的变量 和 未赋值的变量 执行 typeof 操作都返回undefined值


判断数据类型的几种方式

typeof

instanceof

  [] instanceof Array; // 返回true
  [] instanceof Object;// 返回true

constructor

   false.constructor == Boolean;           // true
   "123".constructor == String;            // true
   new Number(123).constructor == Number;  // true
   [].constructor == Array;                // true
   new Function().constructor == Function; // true
   new Date().constructor == Date;         // true
   document.constructor == HTMLDocument;   // true
   window.constructor == Window;           // true
   new Error().constructor == Error;       // true

Object.prototype.toString.call()

   Object.prototype.toString.call(‘123‘) ;   // [object String]
   Object.prototype.toString.call(123) ;     // [object Number]
   Object.prototype.toString.call(false) ;   // [object Boolean]

原文:https://www.cnblogs.com/nangezi/p/14205406.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!