如何判断一个对象是数组还是对象

1.typeof

typeof运算符返回变量或表达式的类型: 数组跟对象都返回object

typeof [];     // "object" 

typeof {}; // "object" 

typeof  0  //返回"number"

typeof  " "   //返回"string"

typeof  "Bill"  //返回"string"

typeof true   //返回"boolean"

typeof false  //返回"boolean"

2.instanceof

数组也是对象的一种,使用instanceof都会返回true

 var arr = new Array();
 var arr = ['aa','bb','cc'];
 var obj = {
   	a: 'aa',
   	b: 'bb',
  	c: 'cc'
 };
 console.log(arr instanceof Array); //true
 console.log(arr instanceof Object); //true
 console.log(obj instanceof Array); //false
 console.log(obj instanceof Object); //true
   

3.constructor

var arr = ['aa','bb','cc'];
var obj = {
'a': 'aa',
'b': 'bb',
'c': 'cc'
};
console.log(arr.constructor === Array); //true
console.log(arr.constructor === Object); //false
console.log(obj.constructor === Object); //true

4.Object.prototype.toString.call()

Object.prototype.toString.call()方法可以精准判断变量类型,它返回[object constructorName]的字符串格式,这里的constructorName就是call参数的函数名

var a = NaN;
var b= '222';
var c = null; 
var d = false;
var e = undefined;
var f = Symbol();
var arr = ['aa','bb','cc'];
var obj = {
'a': 'aa',
'b': 'bb',
'c': 'cc'
};
var res = Object.prototype.toString.call(arr);
console.log(res); //[object Array]
var res2 = Object.prototype.toString.call(obj);
console.log(res2); //[object Object]
var res3 = Object.prototype.toString.call(a);
console.log(res3); //[object Number]
var res4 = Object.prototype.toString.call(b);
console.log(res4); //[object String]
var res4 = Object.prototype.toString.call(c);
console.log(res4); //[object Null]
var res5 = Object.prototype.toString.call(d);
console.log(res5); //[object Boolean]
var res6 = Object.prototype.toString.call(e);
console.log(res6); //[object Undefined]
var res7 = Object.prototype.toString.call(f);
console.log(res7); //[object Symbol]
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值