javascript中 typeof,instanceof类型检测方式

在js中的类型检测基本有三种方式,分别有它们的应用场景:
1、typeof:主要用于检测基本类型.:

typeof undefined;//=> undefined
typeof 'a';//=> string
typeof 1;//=> number
typeof true;//=> boolean
typeof {};//=> object
typeof [];//=> object
typeof function() {};//=> function
typeof null;//=> object

2、instanceof:主要用于检测引用类型(左边是对象,右边是函数.根据对象的原形链往上找,如果原形链上有右边函数.prototype,返回true;否则返回false)

var obj = {}; obj instanceof Object; //=> true; 
var arr = []; arr instanceof Array; //=> true;
var fn = function() {}; fn instanceof Function; //=> true;

3、Object.prototype.toString.call(sth):由于原形链的检测有漏洞(原型是可以改变的),所以会造成检测结果不准确,所以可以采用此种形式.

var toString = Object.prototype.toString;
toString.call(undefined);//=> [object Undefined]
toString.call(1);//=> [object, Number]
toString.call(NaN);//=> [object, Number]
toString.call('a');//=> [object, String]
toString.call(true);//=> [object, Boolean]

toString.call({});//=> [object, Object]
toString.call(function() {});//=> [object, Function]
toString.call([]);//=> [object, Array]
toString.call(null);//=> [object, Null]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值