js数据类型判断
- 0
#讨论区
00条评论
实时对话
loading...
利用二进制检测,二进制前3位存储
基于原型链检查
[] instanceof Array
javascript
javascript
缺点:在自身实例上判断、容易被修改
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
function 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);
}
}
[].constructor===Array
Array.prototype.isPrototypeOf([])
Object.getPrototypeOf([]) === Array.prototype;