[JS] 4 ways to distinguish between arrays and objects, handwritten instanceof method

The commonly used method to distinguish data types is typeof, but the result of the typeof method is object for arrays and objects, so we generally use the following four methods to distinguish:

  1. instanceof method

[] instanceof Array;//true
var obj = {};
obj instanceof Array;//false

// 注意:数组也是继承的Object
Array instanceof Object // true
  1. constructor property

[].constructor;//Array(){}
var obj = {};
obj.constructor;//Object(){}
  1. es5 new isArray method

Array.isArray([]);//true
Array.isArray({});//false
  1. toString method

Object.prototype.toString.call([]);//"[object Array]"
Object.prototype.toString.call({});//"[object Object]"

During the interview, you may ask how to write an instanceof method by hand. The code is as follows:

// instanceof方法可以检测 前者是否继承了后者的原型对象  是否可以获得后者原型对象的属性和方法
 function myInstanceOf(l, r) {
            while (1) {
                if (l.__proto__ === r.prototype) {
                    return true
                }
                if (l.__proto__ == null) {
                    return false
                }
                l = l.__proto__
            }
        }

Guess you like

Origin blog.csdn.net/Andye11/article/details/129101117