6 ways to detect arrays

Array is of type Object, which is a reference type, so typeof cannot be used to determine its specific type. The following methods are several ways to judge the array:

1. Instanceof operator

It is mainly to judge whether a certain instance (arr) belongs to a certain object.

let arr = [1,2,3];
console.log(arr instanceof Array); //true
2、constructor

Determine whether the constructor of the instance (arr) is equal to an object.

let arr = [1,2,3];
console.log(arr.constructor == Array); //true
3、isArray

ES5 adds an array method to determine whether an array is an array.

let arr = [1,2,3];
console.log(Array.isArray(arr)); //true
4、Object.getPrototypeOf()

The Object.getPrototypeOf() method returns the prototype of the specified object and compares it with the prototype of Array.

let arr = [1,2,3];
console.log(Object.getPrototypeOf(arr) == Array.prototype); //true
5. isPrototypeOf on the Array prototype chain

Array.prototype represents the prototype of Array's constructor; the
isPrototypeOf() method can determine whether an object exists in the prototype chain of another object.

let arr = [1,2,3];
console.log(Array.prototype.isPrototypeOf(arr)); //true
6、Object.prototype.toString.call()

Convert the object into a string and compare it with a known object.

let arr = [1,2,3];
console.log(Object.prototype.toString.cal(arr) == '[object Array]'); //true

Guess you like

Origin blog.csdn.net/weixin_43299180/article/details/110916582