判断数组的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

出处:https://www.cnblogs.com/echolun/p/10287616.html

posted @ 2022-05-04 16:38  寒冷的雨呢  阅读(3650)  评论(0编辑  收藏  举报