Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Array is an indispensable data type in the daily development process, how to determine the data type is an array is also a crucial link. In the interview, this is often asked the topic, how to quickly answer the interviewer’s question, let us quickly list…

Array.isArray()

Returns true if the object is Array, false otherwise.

Array.isArray([1, 2, 3]);
// true
Array.isArray({foo: 123});
// false
Array.isArray("foobar");
// false
Array.isArray(undefined);
// false
Copy the code

arr instanceof Array

The instanceof operator is used to check whether the constructor’s prototype property appears on the prototype chain of an instance object.

const arr = [1, 2];
arr instanceof Array  
// true
Copy the code

Array.prototype.isPrototypeOf()

The isPrototypeOf() method tests whether an object exists on the prototype chain of another object.

IsPrototypeOf () differs from the instanceof operator. In the expression “object instanceof AFunction”, the prototype chain of object is checked against AFunction. Prototype, not against AFunction itself

arr.constructor === Array

Determines whether the constructor of an object is an array.

Constructor is a special method for creating and initializing objects created by a class. If the constructor of the object is Array, then the object can be created by the Array constructor, which means that it is an Array.

Object.getPrototypeOf(arr) === Array.prototype

The object.getProtoTypeof (Object) method returns the prototype of the specified Object.

If the object’s prototype is array.prototype, you can also determine that the object is an Array.

Object.prototype.toString.call(arr) === '[object Array]'

The toString() method returns a string representing the object.

Each object has a toString() method, which is called automatically when the object is represented as a text value, or when an object is referenced as an expected string. By default, the toString() method is inherited by each Object. If this method is not overridden in a custom object, toString() returns “[Object type]”, where type is the class of the object

conclusion

If this article helped you, please like 👍 and follow ⭐️.

If there are any errors in this article, please correct them in the comments section 🙏🙏.

Reference:

isPrototypeOf

GetPrototypeOf