JS中的数据类型
- number
- string
- boolean
- null
- undefined
- symbol
- bigint
检测办法
- typeof 运算符
- instanceof [原型链]
- constructor [构造函数]
- Object.prototype.toString.call([value]) 检测数据类型
- Array.isArray([value]) 检测一个值是否为数组
typeof
- 可以识别基本数据类型 null为object
- 引用类型为object和function
利用二进制检测,二进制前3位存储
- 000: 对象
- 010: 浮点数
- 100:字符串
- 110:布尔
- 1:整数
- null的二进制全为000所以是object
instanceof
基于原型链检查
[] instanceof Array
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);
}
}
Contructor
[].constructor===Array
缺点:在自身实例上判断、容易被修改
Object.prototype.toString.call()
Object.prototype.toString({}) // "[object Object]"
Object.prototype.toString.call([]) //"[object Array]"
Object.prototype.toString.call('1') // "[object String]"
Array.isArray
判断是否是数组
Array.isArray([]) // true
Array.isArray(1) // false
Object.prototype.isPrototypeOf
Array.prototype.isPrototypeOf([])
Object.getPrototypeOf
Object.getPrototypeOf([]) === Array.prototype;