js determines whether an object or an array

1. For Javascript 1.8.5 (ECMAScript 5), the variable name .isArray( ) can achieve this purpose

1 var a=[];
2 var b={};
3 Array.isArray(a);//true
4 Array.isArray(b)//false

 

2. If you just use typeof to check the variable, whether it is an array or an object, it will return 'objec'. A possible answer to this question is to check if the variable is an object,

And check whether the variable has a numeric length (the length may also be 0 when it is an empty array, and the length of the object is undefined).

 

var a=[];
var b={};
typeof a === 'object' && !isNaN(a.length)//true
typeof b === 'object' && !isNaN(b.length)//false

 

3. Call the toString( ) method to try to convert the variable to a string representing its type. 

var a=[];
var b={};
Object.prototype.toString.call(a)  === '[object Array]'//true
Object.prototype.toString.call(b)  === '[object Array]'//false

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325473232&siteId=291194637