一. 基本数据类型
`Undefined`、`Null`、`Boolean`、`Number`、`String`、`Symbol`、`BigInt`(es6新增)。
二. 复杂数据类型(引用数据类型Object)
`Array`、`Function`、`Date`、`RegExp`、`Error`、`Arguments` ....
三. 检测数据类型的方法
typeof这种只能粗略的检测不同数据的类型 注意: 这种方式返回的类型都是小写的字符串 只要是引用类型他都会返回object, 其中null这个基本数据类型返回的也是object, 因为在原型链上看Object.prototype.proto = null 所以,null其实就是一个空的对象的引用
console.log(Object.prototype.__proto__ === null)//true
console.log(Object.prototype.__proto__)//null
-
instanceof
instanceof 是用来判断 A 是否为 B 的实例,表达式为:A instanceof B,如果 A 是 B 的实例。 instanceof 检测的是原型 具体请看这里 -
利用
constructor具体请看这里 -
Object.prototype.toString.call()这种方法是最好的,可以返回准确的类型判断 参数: 要检测的对象 返回值: 带有Object的数组字符串 注意:类型的首字母是大写的 如果想要变成小写,可以调用字符串的toLowerCase()方法
const obj = {
name: 'zh'
}
const arr = [1,2,3]
const typeObj = Object.prototype.toString.call(obj).slice(8, -1)
const typeArr = Object.prototype.toString.call(arr).slice(8, -1)
console.log(typeObj)//"Object"
console.log(typeArr)//"Array"
四. 封装一个最全类型检测函数
function type(target) {
//先利用typeof操作符判断
let res = typeof target
// 保存引用类型和基本包装类型的情况
let temp = {
"[object Object]": 'object',
"[object Array]": 'array',
"[object String]": 'string - object',
"[object Number]": 'number - object',
"[object Boolean]": 'boolean - object'
}
// 判断传入的是否为空
if(target === null) {
return null
}else if(res === 'object') {
let str = Object.prototype.toString.call(target)
return temp[str]
}else {
return res
}
}
console.log(type({name: 'zh'}))//object
console.log(type([]))//array
console.log(type(null))//null
console.log(type(3))//number
console.log(type('zh'))//string
let a
console.log(type(a))//undefined
console.log(type(true))//boolean
console.log(type(function() {}))//function
console.log(type(new Number()))//number - object
console.log(type(new String()))//string - object
console.log(type(new Boolean()))//boolean - object