判断数组的4种方法
1.通过instanceof判断
instanceof运算符用于检验构造函数的prototype属性是否出现在对象的原型链中的任何位置,返回一个布尔值
let a = [];
a instanceof Array; //true
let b = {};
b instanceof Array; //false
//instanceof 运算符检测Array.prototype属性是否存在于变量a的原型链上
//显然a是一个数组,拥有Array.prototype属性,所以为true
2.通过constructor判断
实例的构造函数属性constructor指向构造函数,通过constructor属性可以判断是否为一个数组
let a = [7,8,9];
a.constructor === Array; //true
3.通过Object.prototype.toString.call()判断
Object.prototype.toString.call()可以获取到对象的不同类型
let a = [7,8,9];
Object.prototype.toString.call(a) === '[Object Array]'; //true
4.通过Array.isArray()判断
Array.isArray()用于确定传递的值是否是一个数组,返回一个布尔值
let a = [7,8,9];
Array.isArray(a); //true
有个问题是Array.isArray()是ES5新增的方法,目的就是提供一个稳定可用的数组判断方法,对于ES5之前不支持此方法的问题,我们其实可以做好兼容进行自行封装,如下:
if(!Array.isArray){
Array.isArray = function(argument){
return Object.prototype.toString.call(argument) === '[object Array]';
}
};
5.补充:typeof
typeof 只能检测 基本数据类型,包括boolean、undefined、string、number、symbol,而null ,Array、Object ,使用typeof出来都是Object,函数的typeof 是function 无法检测具体是哪种引用类型。
console.log(typeof(100),1); result: number 1
console.log(typeof("name"),2); result: string 2
console.log(typeof(false),3); result: boolean 3
console.log(typeof(null),4); result: object 4
console.log(typeof(undefined),5); result: undefined 5
console.log(typeof([]),6); result: object 6
console.log(typeof(Function),7); result: function 7
择善人而交,择善书而读,择善言而听,择善行而从。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通