Learning record: JavaScript judgment array

1. instanceof

The explanation on MDN is : the instanceof operator is used to detect whether constructor.prototype exists in the prototype chain of the parameter object.

The syntax is: object (an instance object) instanceof constructor (a constructor)

let arr = [1, 3];

console.log(arr instanceof Array);   // true
// 值得注意的是:Array是Object的子类,下面也会输出true
console.log(arr instanceof Object);  // true

2. constructor

The explanation on w3school is : the constructor attribute returns the constructor for creating this object.

The syntax is: object.constructor

let arr = [1, 3];

console.log(arr.constructor);           // ƒ Array() { [native code] }  指向Array
console.log(arr.constructor == Array);  // true

3. proto and prototype

Explain that objects have unique proto attributes and functions have unique prototype attributes. When generating objects, the proto attributes of the objects point to the prototype attributes of the function.

This is judged by the prototype chain.

let arr = [1, 3];

console.log(arr.__proto__ === Array.prototype);  // true

4. toString()

The explanation on MDN is : every object can detect the type of the object through Object.prototype.toString(), it needs to be called in the form of Function.prototype.call() or Function.prototype.apply(), and the pass needs to be checked The object as the first parameter is called thisArg.

let arr = [1, 3];

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

5.isPrototypeOf()

It is also judged by the prototype chain here to check whether the Array is on the prototype chain of arr.

let arr = [1, 3];

console.log(Array.prototype.isPrototypeOf(arr));   // true

6. isArray()

The explanation on MDN is : Array.isArray() is used to determine whether the passed value is an array.

This is the method provided by es6, which can be regarded as the encapsulated fourth method toString().


Thanks for reading, the article is only used as study notes.

Guess you like

Origin blog.csdn.net/qq_37992222/article/details/112342597