JS judges whether a variable is an array, what methods can you write? (JavaScript interview questions)

Method 1: isArray

var arr = [1,2,3];
console.log( Array.isArray( arr ) );

Method 2: instanceof [Writable or not)

var arr = [1,2,3];
console.log( arr instanceof Array );

Method 3: Prototype prototype

var arr = [1,2,3];
console.log( Object.prototype.toString.call(arr).indexOf('Array') > -1 );

Method 4: isPrototypeOf()

var arr = [1,2,3];
console.log(  Array.prototype.isPrototypeOf(arr) )

Way 5: constructor

var arr = [1,2,3];
console.log(  arr.constructor.toString().indexOf('Array') > -1 )

During the interview, you can actually type the following 4 points.

1、Object.prototype.toString.call()

2. Judging obj.__proto__===Array.prototype through the prototype chain

3、Array.isArray()

4、instanceof

Guess you like

Origin blog.csdn.net/weixin_54614831/article/details/126433632