判断javascript的对象类型

1.typeof

形如 :

typeof undefined                //undefined 
typeof 'qw'                     //string
typeof 1                        //number
typeof true                     //Boolean
typeof function(){}             //function
//不区分null、{}、数组
typeof null                     //object
typeof {}                       //object
typeof []                       //object

返回类型有: ‘undefined’ “string” ‘number’ ‘boolean’ ‘function’ ‘object’
缺点: 对于object类型不能细分是什么类型 ,比如null、{}、数组
优点: 对undefined的判断 'undefined’的应用

2.instanceof

instanceof用于判断一个变量是否某个对象的实例,最终结果是一个布尔值
形如 :


var d = new String('test'); 
d instanceof String === true;

null instanceof Object        //false
undefined instanceof Object   //false

[] instanceof Object //true
[] instanceof Array //true
Function instanceof Object //true
Function instanceof Function //true


var a = 'qwqwq';
a instanceof String //false
"awqwqw" instanceof String //false

返回的类型有: String Number Boolean Function Object Array Date
优点: 可以区分null和undefined不为Object
缺点: 区分不清除 数组,Function,和string,number类型必须是new生成的对象,直接量无法判断。

3.constructor

形如:


var x = []; 
x.constructor === Array;
null.constructor === Object //Cannot read property 'constructor' of null
undefined.constructor === undefined //Cannot read property 'constructor' of undefined

优点: 可以返回继承的类型
缺点: 不能对象的细分,如继承 必须手动修正,不能验证null和undefined

4.Object.prototype.toString.call();

Object.prototype.toString.call([]) //"[object Array]"
Object.prototype.toString.call({}) //"[object Object]"
Object.prototype.toString.call(new Date()) //"[object Date]"
Object.prototype.toString.call("") //"[object String]"
Object.prototype.toString.call(null) //"[object Null]"
Object.prototype.toString.call(undefined) //"[object Undefined]"
Object.prototype.toString.call(1) //"[object Number]"
Object.prototype.toString.call(Function) //"[object Function]"

优点: 通用,返回"[objectString]" 具体object的类型
缺点: 不能返回继承的类型

5.Array.prototype.isPrototypeOf(obj)

Array.prototype.isPrototypeOf([])  //true
Array.prototype.isPrototypeOf({})  //false
Object.prototype.isPrototypeOf([]) //true
Object.prototype.isPrototypeOf({}) //true

优点: 指定判断数组类型
缺点: 不能辨别数组,对象,等引用类型,不辨别,基本类型

6.Array.isArray()

Array.isArray({}) //false
Array.isArray([]) //true

优点: 精准的判断数组
缺点: 只能判断是否是数组

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值