How does JavaScript determine whether a variable is an array or an object

target instanceof type

Note: typeof cannot be used, because except for primitive types and functions, all are objects. (Including null); Do not use Object to test, because Array belongs to a subclass of object 

var a = {}
var b = []

// 【注意】不要用Object来测试,因为Array属于Object的子类
console.log(a instanceof Array) //false
console.log(b instanceof Array) //true

target.constructor

Since each instance will inherit the properties of the prototype, and the prototype's constructor property will point to its own constructor; custom classes can be displayed

var a = {}
var b = []

console.log(a.constructor) // [Function: Object]
console.log(b.constructor) //[Function: Array]

Object.prototype.toString.call(target)

1. Each object comes with a default toString function to print the type of the object

2. However, some custom objects may rewrite toString. Therefore, call from the original object prototype, and then use call to replace this environment

3. Unable to display custom classes, all will display Object

var a = {}
var b = []

console.log(Object.prototype.toString.call(a)) // [object Object]
console.log(Object.prototype.toString.call(b)) // [object Array]

 

 

Reprinted from: https://www.wolai.com/mary/rPktXJ2xocawfXnX1vqTeD

Guess you like

Origin blog.csdn.net/wanghongpu9305/article/details/114127251