js判断是对象及类型

1.typeof

typeof 0;  //number;
typeof true;  //boolean;
typeof undefined;  //undefined;
typeof "hello world"   //string;
typeof function(){};   //function;

typeof null; //object
typeof {};  //object;
typeof []; //object

 

2.instanceof

var a={};
a instanceof Object  //true
a intanceof Array     //false
var b=[];
b instanceof Array  //true
b instanceof  Object //true

因为数组属于object中的一种,所以数组instanceof object,也是true.

var c='abc';
c instanceof String; //false
var d=new String();
d instanceof String  //true

instanceof不能区分基本类型string和boolean,除非是字符串对象和布尔对象。如上例所示。

3.constructor 

除了undefined和null,其他类型的变量均能使用constructor判断出类型.

区分类型,
除了对象和数组,其他用typeof去判断,
区分 数组和对象

arr.constructor==Array  //true
arr.constructor==Object //false
Object.prototype.toString.call(obj) === '[object Object]' obj是对象
Object.prototype.toString.call(obj) === '[object Array]'  obj是数组

4.Object.prototype.toString.call()   ---------最好用

Object.prototype.toString.call(123)
//"[object Number]"

Object.prototype.toString.call('str')
//"[object String]"

Object.prototype.toString.call(true)
//"[object Boolean]"

Object.prototype.toString.call({})
//"[object Object]"

Object.prototype.toString.call([])
//"[object Array]"

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值