During the interview on contract lock, I asked how to judge whether an array is an object, and only answered the isArray() method in ES6. When the interviewer continued to remind me of the method on the prototype chain, I couldn't remember it, so I recorded it.
1.typeof
typeof can judge the basic data type, but the reference data type is actually object, so it is impossible to judge whether it is an array or an object
let num=1;
console.log(typeof num) //number
let str="222";
console.log(typeof str) //string
console.log(typeof null) //object
console.log(typeof undefined) //undefined
console.log(typeof NaN) //number
2. Use Array.isArray()
let obj={}
let arr=[]
console.log(Array.isArray(obj)) //false
console.log(Array.isArray(arr)) //true
3. Judgment constructor
Through the prototype chain, we can see that the prototype of the function object points to a display prototype, and there is a constructor on the display prototype that can point back to the function.
obj is constructed by the new Object function
arr is constructed by the new Array function
let obj={}
let arr=[]
console.log(obj.constructor()) // {}
console.log(arr.constructor()) //[]
4. You can judge whether it is an instance object through instanceof
let obj={}
let arr=[]
console.log(obj instanceof Array) //false
console.log(arr instanceof Array) //true
console.log(obj instanceof Object) //true
console.log(arr instanceof Object) //true
5.Object.prototype.toString.call()
let obj={}
let arr=[]
console.log(Object.prototype.toString.call(obj)) //[object Object]
console.log(Object.prototype.toString.call(arr)) //[object Array]