本站目前升级了全新主题zhime,该主题色彩更清新明亮。售价99元/套,你值得拥有,后台配置全,永久更新。另外还有Next.js版本!😃

JS如何区分对象和数组

很多朋友首先想到的是用typeof来判断,其实typeof一般测试基本类型(Undefined、Null、Boolean、Number、String),对引用类型一律返回object(有一个特殊,Function引用类型返回Function)。

所以typeof用于判断是对象还是数组是没有作用的。

这里简单介绍下两个方法:

方法一

直接使用内置方法isArray来判断,当然,只能判断是否是数组,对象还需要另外再判断

code
const a = [1, 2, 3, 4];
const b = {"name": "智言"};
console.log(Array.isArray(a)) //true  
console.log(Array.isArray(b)) //false

方法二

使用constructor来判断

code
const a = [2, 4, 3];
const b = {"name": "智言"};
console.log(a.constructor == Array; //true
console.log(b.constructor == Object); //true

方法三

instanceOf运算符。左边是子对象(待测试对象),右边是父构造函数。

凡是用new()构造函数创建出的对象,都称之为构造函数的实例。

code
const obj = {"name": "智言"};  
const arr = [1, 2, 3];  
console.log((obj instanceof Array)); //false  
console.log((arr instanceof Array)); //true

读完了点一下,作者能得积分

赞赏

如果这篇内容帮到了你,不妨请作者喝杯咖啡

分享 微博 QQ

发表评论

发表评论