利用二进制检测,二进制前3位存储
基于原型链检查
[] instanceof Array
javascriptfunction isInstanceOf(instance, constructor) { const list = ['string', 'number', 'boolean', 'undefined', 'symbol'] const type = typeof instance const isBasicVal = instance === null || list.indexOf(type) > -1 const prototype = constructor.prototype let proto = isBasicVal ? null : instance.__proto__ while (true) { if (proto === null) return false; if (proto === prototype) return true; proto = Object.getPrototypeof(proto); } }
javascript[].constructor===Array
缺点:在自身实例上判断、容易被修改
Object.prototype.toString({}) // "[object Object]"
Object.prototype.toString.call([]) //"[object Array]"
Object.prototype.toString.call('1') // "[object String]"
判断是否是数组
Array.isArray([]) // true
Array.isArray(1) // false
javascript
javascript
Array.prototype.isPrototypeOf([])
Object.getPrototypeOf([]) === Array.prototype;