Summary of various methods for JavaScript to determine whether it is an array

Summary of various methods for JavaScript to determine whether it is an array

Preface

In our daily development, we often have the need to determine the type of a value. Today we summarize several common JavaScript methods used to determine whether it is an array.

Array.isArray

Array.isArray() is a new method added in ES5, which is used to determine whether the passed value is an array. If it is an array, it returns true, otherwise it returns false.

let arr = [];
console.log(Array.isArray(arr)); // true

The following function calls all return true:

Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array("a", "b", "c", "d"));

One thing to note is that Array.prototype is actually also an array.

Array.isArray(Array.prototype); // true

The following function calls all return false:

Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray('Array');
Array.isArray(true);
Array.isArray(false);
Array.isArray(new Uint8Array(32))
Array.isArray({ __proto__: Array.prototype });

The compatibility is as shown below:

As you can see, new versions of mainstream browsers all support this method and can be used with confidence.

constructor

Each instance of Object has a constructor, which is used to store the function used to create the current object.

let arr = [];
console.log(arr.constructor === Array); // true

It should be noted that the constructor is at risk of being modified, and the judgment result may not be accurate, for example:

let arr = [1, 2, 3];
arr.constructor = function () { }
console.log(arr.constructor === Array); // false

It is generally not recommended to use the constructor to determine whether it is an array. We just need to know that there is such a method.

instanceof

The instanceof operator is used to detect whether the prototype property of the constructor function appears in the prototype chain of an instance object. For example:

// Define the constructor function C() {}
function D() {}

var o = new C();

o instanceof C; // true, because Object.getPrototypeOf(o) === C.prototype

o instanceof D; // false, because D.prototype is not in o's prototype chain o instanceof Object; // true, because Object.prototype.isPrototypeOf(o) returns true
C.prototype instanceof Object; // true, same as above

The usage of instanceof to determine whether it is an array is as follows:

let arr = [];
console.log(arr instanceof Array); // true

There are two points to note when using instanceof:

  • The prototype of the constructor and the prototype chain of the instance may change, so the judgment result may not remain unchanged.
  • Using instanceof in a page script with an iframe may result in incorrect results, because the iframe has an independent global environment, and different global environments have different global objects and thus different built-in type constructors.

isPrototypeOf

isPrototypeOf() can be used to test whether an object exists in the prototype chain of another object. Usage is as follows:

function Foo() {}
function Bar() {}
function Baz() {}

Bar.prototype = Object.create(Foo.prototype);
Baz.prototype = Object.create(Bar.prototype);

var baz = new Baz();

console.log(Baz.prototype.isPrototypeOf(baz)); // true
console.log(Bar.prototype.isPrototypeOf(baz)); // true
console.log(Foo.prototype.isPrototypeOf(baz)); // true
console.log(Object.prototype.isPrototypeOf(baz)); // true

If you want to use isPrototypeOf to determine whether the incoming parameter is an array, you can use it like this:

let arr = [];
console.log(Array.prototype.isPrototypeOf(arr)); // true

Object.prototype.toString

Every object has a toString() method that is automatically called when the object is represented as a text value, or when an object is referenced in a way that expects a string.

By default, the toString() method is inherited by every Object object. If this method is not overridden in a custom object, toString() returns the string "[object type]" where type is the type of the object.

You can use toString() to get the type of each object. In order for each object to be detectable via Object.prototype.toString(), it needs to be called as Function.prototype.call() or Function.prototype.apply(), passing the object to be checked as the first argument, called thisArg. Usage is as follows:

var toString = Object.prototype.toString;

toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]

//Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]

If you want to determine whether an object is an array, you can use it like this:

let arr = [];
console.log(Object.prototype.toString.call(arr) === "[object Array]"); // true

Compatibility is as follows:

typeof

When it comes to judging types, many people may think of the typeof method. Let's review the content related to typeof here.

The typeof operator returns a string indicating the type of its unevaluated operand.

console.log(typeof 42); // "number"
console.log(typeof 'blubber'); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undeclaredVariable); // "undefined"

The possible return values ​​of typeof are as follows:

As can be seen from the figure above, array objects belong to "any other object", so the typeof return value of array objects is "object":

let arr = [];
console.log(typeof arr); // "object"

Therefore, we should try to avoid using typeof.

Summarize

The above are several ways to determine whether a value is an array. Of course, some are useful and some are not, but no matter what, it is always good to know that there is such a thing. To summarize:

  • The best method is Array.isArray, but it is not supported by IE8 and below.
  • If compatibility is a concern, you can use Object.prototype.toString.

This is the end of this article about how to determine whether something is an array using JavaScript. For more information about how to determine whether something is an array using JavaScript, please search previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript Array Detailed Summary
  • Common array operations in JavaScript
  • Detailed explanation of JavaScript array deduplication
  • JavaScript Array Methods - Systematic Summary and Detailed Explanation
  • Summary of examples of common methods of JavaScript arrays
  • JS uses map to integrate double arrays
  • JavaScript array merging case study
  • Example of converting JavaScript flat array to tree structure
  • JavaScript commonly used array deduplication actual combat source code
  • Basic use of javascript array includes and reduce
  • js converts a multidimensional array into a one-dimensional array and then reorders it
  • How to parse mixed array objects into list collection of entity class in json
  • Commonly used JavaScript array methods

<<:  How to completely delete the MySQL 8.0 service under Linux

>>:  Introduction to Nginx regular expression related parameters and rules

Recommend

Rainbow button style made with CSS3

Result: Implementation code: html <div class=&...

Realizing tree-shaped secondary tables based on angular

First look at the effect: Code: 1.html <div cl...

About converting textarea text to html, that is, carriage return and line break

Description: Change the carriage return in the tex...

The implementation principle of Mysql master-slave synchronization

1. What is MySQL master-slave synchronization? Wh...

WeChat applet implements calculator function

WeChat Mini Programs are becoming more and more p...

React Native JSI implements sample code for RN and native communication

Table of contents What is JSI What is different a...

Vue mobile terminal realizes finger sliding effect

This article example shares the specific code for...

Use render function to encapsulate highly scalable components

need: In background management, there are often d...

How to use iostat to view Linux hard disk IO performance

TOP Observation: The percentage of CPU time occup...

VMware configuration VMnet8 network method steps

Table of contents 1. Introduction 2. Configuratio...

How to deploy tomcat in batches with ansible

1.1 Building the Directory Structure This operati...

MySQL backup and recovery design ideas

background First, let me explain the background. ...