current position:Home>Summary of JavaScript methods to determine whether it is an array

Summary of JavaScript methods to determine whether it is an array

2021-08-26 06:16:09 Programming samadhi

Preface

We are in daily development , There is often a need to judge a value type , Today, we will summarize several common methods to determine whether it is an array JavaScript Method .

Array.isArray

Array.isArray() yes ES5 New method , Used to determine whether the passed value is an array , If it's an array , Then return to true, Otherwise return to 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 : Actually Array.prototype It's 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 shown in the figure below :

image-20210822221555090

You can see , New mainstream browsers support this method , Safe to use .

constructor

Object Every instance of has a constructor constructor, Used to save the function used to create the current object

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

It should be noted that ,constructor There is a risk of being modified , The judgment is not necessarily accurate , such as :

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

Generally not recommended constructor To determine whether it is an array , We just need to know that there is such a way .

instanceof

instanceof Operator is used to detect the prototype Whether the attribute appears in the prototype chain of an instance object . for instance :

//  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  be not in  o  On the prototype chain 

o instanceof Object; // true, because  Object.prototype.isPrototypeOf(o)  return  true
C.prototype instanceof Object; // true, ditto 

use instanceof To determine whether it is an array, the usage is as follows :

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

Use instanceof Two things to note :

  • Constructor's prototype and The prototype chain of instances may change , So the result of judgment is not necessarily invariable .
  • There is iframe Used in page scripts instanceof, You may get the wrong result , because iframe Have an independent global environment , Different global environments have different global objects , So you have different built-in type constructors .

isPrototypeOf

isPrototypeOf() It can be used to test whether one 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 , It can be used in this way :

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

Object.prototype.toString

Each object has one toString() Method , When the object is represented as a text value , Or an object is automatically called when it is referenced in the expected string way .

By default ,toString() The method is each Object Object inheritance . If this method is not overridden in the custom object ,toString() return "[object type]" character string , among type It's the type of object .

Can pass toString() To get the type of each object . For every object to pass through Object.prototype.toString() To detect , Need to be Function.prototype.call() perhaps Function.prototype.apply() To call , Pass the object to be checked as the first parameter , be 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 judge whether an object is an array , It can be used in this way :

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

Compatibility is as follows :

image-20210822225754452

typeof

When it comes to judging types , Maybe a lot of people will think of typeof Method , Let's review here typeof Related content .

typeof The operator returns a string , Represents the type of uncomputed operand .

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

typeof The possible return values are as follows :

As you can see from the picture above , The array object belongs to “ Anything else ”, So the of array objects typeof The return value is “object”:

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

therefore , We should try to avoid using typeof.

summary

The above are several methods to judge whether a value is an array , Of course, there are good and bad , But anyway , We know it's always good to have such a thing . To sum up :

  • The best way to use is Array.isArray, It just doesn't support IE8 And the following .
  • If you want to consider compatibility , You can use Object.prototype.toString.

~

~ The end of this paper , Thank you for reading !

~

Learn interesting knowledge , Make interesting friends , Create interesting souls !

Hello everyone , I am a 〖 The samadhi of programming 〗 The author of Hermit King , My official account is 『 The samadhi of programming 』, Welcome to your attention , I hope you can give me more advice !

You come to , With expectations , I have ink to greet ! You go back , No matter gain or loss , Only with lingering charm !

Knowledge and skills are equally important , Both internal and external skills , We should grasp both theory and practice 、 Hard on both hands !

copyright notice
author[Programming samadhi],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210826061607129q.html

Random recommended