JS检测类型

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)  true
console.log(f instanceof Date)    true
console.log(h instanceof Function) true

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

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

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

alert(f.constructor === Date) -----------> true
alert(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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值