typeof 判断原始数据类型时,除了null 之外都能判断正确
typeof 1 // "number"
typeof "abc" // "string"
typeof true // "boolean"
typeof Symbol() // "symbol"
typeof Undefined // "undefined"
typeof null // "object"
typeof 判断复杂数据类型时,除了函数能判断正确之外,都返回object,所以typeof并不能准确判断类型
typeof [] // "object"
typeof {} // "object"
typeof function () {} // "function"
判断复杂数据类型时可以通过 instanceof 进行判断,instanceof通过原型链来判断,它判断前一个参数是否能在后一个参数的原型链中找到,找到返回true,否则返回false
const person1 = new Person()
person1 instanceof Person // true
const str = 'abc'
str instanceof String // false
结合typeof 和 instancof 可以判断一个变量 obj1 的数据类型:
- 使用typeof 判断,如果它是非null的原始数据类型,则判断完成;如果返回object 则可能是null 或 复杂数据类型
- 通过obj1 instanceof Object ,如果返回为false,则 obj1为null类型;如果返回 true则是复杂数据类型
- 通过instanceof 依次判断obj1 的类型