- 数据类型的分类
- 7大基本数据类型
- 注意没有NaN(恶心东西)
- null typeof(null) ==object 历史bug
MDN
类型 | typeof |
---|---|
undefined | typeof instance === “undefined” |
Boolean | typeof instance === “boolean” |
Number | typeof instance === “number” |
String | typeof instance === "string |
BigInt(MDN) | typeof instance === “bigint” |
Symbol | typeof instance === “symbol” |
null | typeof instance === “object”(bug) |
- 复杂数据类型Object
- 包括Array、Function、Date、RegExp、Error、Arguments
- typeof(MDN)
let {
log
} = console
let a = {}
function b() {}
let c = []
log(typeof(NaN))
log(typeof(a)) //object
log(typeof(b)); //function
log(typeof(c)); //object
log(typeof(NaN)) //number
log(typeof(Function))//function
可以看出大多数都检测出来了(null==object)
但:
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';
- instanceof(MDN)检测自定义类型
object instanceof constructor
检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上
- instanceof 可以准确判断对象(引用)类型,但是不能准确检测原始类型。
- 由于我们可以随意修改原型的指向导致检测结果不准确,所以这种方法是不安全的。
function Foo() {
}
Object instanceof Object // true
Function instanceof Function // true
Function instanceof Object // true
Foo instanceof Foo // false
Foo instanceof Object // true
Foo instanceof Function // true
这里看懂了原型链也就懂了,可以看这
- Object.prototype.toString.call(obj)检测对象的类型
Object.prototype.toString() 返回 “[object type]”
Object.prototype.toString.call(obj)
改变它的this指向,将 this 指向要检测的值,即可返回当前检测值的信息。
log(Object.prototype.toString([])) //[object,object]
log(Object.prototype.toString.call([])) //[object,array]
log(Object.prototype.toString.call(null))//[object,Null]
log(Object.prototype.toString.call(undefined))//[object,undefined]
//[object,undefined]没有都号
- constructor
- 除了 null 和 undefined,constructor 可以正确检测出原始类型和对象(引用)类型。
- 由于我们可以随意修改 constructor 导致检测结果不准确,所以这种方法是不安全的。
log([].constructor) //f Array(){}
//log(undefined.constructor)//报错
console.log(null.constructor);报错
- 封装:typeof+toString()
const getType = function(obj) {
let type = typeof obj
if (type !== 'object') {
return type
}
//return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1').toLowerCase()
return Object.prototype.toString.call(obj).split(' ')[1].replace(']', '').toLowerCase()
}
另外判断数组的方法有了吧。
console.log([] instanceof Array)
console.log(getType([]) == 'array');
console.log([].constructor == Array);
console.log(Array.isArray([]));
NaN 用Number.isNaN()把,看到就烦(不咋用)