This is the 22nd day of my participation in the August More Text Challenge

preface

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

Array.isArray

Array.isarray () is a new method in ES5 that determines whether the value passed is an Array, returning true if it is, and false otherwise.

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

The following function calls all return true:

Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array("a"."b"."c"."d"));
Copy the code

Note that array. prototype is also an Array.

Array.isArray(Array.prototype); // true
Copy the code

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 });
Copy the code

The compatibility is shown as follows:

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

constructor

Each instance of Object has its constructor, which holds the function used to create the current Object

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

Note that constructor is at risk of being modified and may not be accurate, for example:

let arr = [1.2.3];
arr.constructor = function () {}console.log(arr.constructor === Array); // false
Copy the code

Using constructor to determine whether an array is an array is generally not recommended; we just need to know that there is such a method.

instanceof

The instanceof operator is used to check whether the constructor’s prototype property appears on the prototype chain of an instance object. Here’s an 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 on o's prototype chain

o instanceof Object; / / true, because the Object. The prototype. IsPrototypeOf (o) returns true
C.prototype instanceof Object; // true

Copy the code

We can use instanceof to check whether it is an array as follows:

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

Two things to note when using Instanceof:

  • Both the constructor’s prototype and the instance’s prototype chain can change, so the result may not always be the same.
  • Using instanceof in a page script with an IFrame can get wrong results because iframe has a separate 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 on the prototype chain of another object. Usage:

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
Copy the code

If you want to use isPrototypeOf to determine whether the passed argument is an array, you can use:

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

Object.prototype.toString

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 the string “[Object type]”, where type is the type of the object.

You can get the type of each object by toString(). To every Object through the Object. The prototype. The toString () to test, need to Function. The prototype. The call () or the Function. The prototype, the apply () in the form of a call, Pass the object to be checked as the first argument, called thisArg. Usage:

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]
Copy the code

If you want to determine whether an object is an array, you can do this:

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

The compatibility is as follows:

typeof

When it comes to determining types, most people probably think of the Typeof method, so let’s review typeof here.

The typeof operator returns a string representing the typeof the unevaluated operand.

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

The possible return values of typeof are as follows:

As you can see from the figure above, the array object belongs to “any other object”, so the typeof return value of the array object is “object” :

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

Therefore, we should avoid typeof as much as possible.

conclusion

So these are a couple of ways to determine if a value is an array, some good and some bad, but anyway, we know it’s a good thing to have. To sum up:

  • The best way to do this isArray.isArray, but IE8 and below are not supported.
  • You can use this if you want to consider compatibilityObject.prototype.toString.

~

Thanks for reading!

~

Learn interesting knowledge, meet interesting friends, shape interesting soul!

Hello everyone, I am the author of “programming Samadhi”, I am king Yi, my public account is “programming Samadhi”, welcome to pay attention, I hope you can give me more advice!

You come, with expectations, I have ink to welcome! You return, no matter gain or loss, only to yu Yun give each other!

Knowledge and skills should be paid equal attention to, internal force and external power should be repaired simultaneously, theory and practice should grasp both hands, both hands should be hard!