JS检测类型

来源:互联网 发布:职称计算机模拟软件 编辑:程序博客网 时间:2024/05/22 16:56

ES中有5种基本数据类型:Undefined、Null、Boolean、Number、String。还有一种复杂数据类型:Object。
例子:

var a;var b = null;var c = true;var d = 4;var e = "five";var f = new Date();var h = function(){alert(111);};

1.最常见的检测方法:typeof

typeof可以检测基本类型值;
tips:

  1. typeof b 也会返回object;
  2. typeof h返回function,即typeof可以判断function类型;
  3. typeof返回的类型都是字符串形式,typeof a == “string”返回true;

缺点:无法检测是什么类型的对象。

2.检测对象类型:instanceof

如果变量是给定引用类型instanceof 操作符就会返回true。所有引用类型的值都是Object 的实例。因此,在检测一个引用类型值和Object 构造函数时,instanceof 操作符始终会返回true。

console.log(f instanceof Object)  trueconsole.log(f instanceof Date)    trueconsole.log(h instanceof Function) true

tips:
instanceof 后面一定要是对象类型,并且大小写不能错。
缺点:
只要用这个操作符来测试实例与原型链中出现过的构造函数,结果就会返回true。

3.根据原型的constructor判断: constructor

实例会共享原型上的constructor属性,该属性指向原型的构造函数,故可以由此判断对象的类型。

alert(f.constructor === Date) -----------> truealert(h.constructor === Function) -------> true

缺点:
1. 当以字面量形式重写原型时会报错;
2. 原型链继承时 A.prototype = new B(); A.construtor指向父类B的构造函数。

instanceof方法不会出现该问题,对象直接继承和间接继承的都会报true

4.通用但很繁琐的方法: prototype

通过Object.prototype.toString方法,可以判断某个对象值属于哪种内置类型(基本类型和引用类型)。

console.log(Object.prototype.toString.call(123)) //[object Number]console.log(Object.prototype.toString.call('123')) //[object String]console.log(Object.prototype.toString.call(undefined)) //[object Undefined]console.log(Object.prototype.toString.call(true)) //[object Boolean]console.log(Object.prototype.toString.call({})) //[object Object]console.log(Object.prototype.toString.call([])) //[object Array]console.log(Object.prototype.toString.call(function(){})) //[object Function]
原创粉丝点击