一、数据类型分类
1、基本数据类型(也称为简单数据类型):字符串、数字、布尔值、undefined、null
2、复杂数据类型:Object(引用类型都是Object的实例)
3、ES6引入的新类型:Symbol
二、基本类型检测,使用typeof操作符
console.log(typeof 1) //number
console.log(typeof 'test') //string
console.log(typeof true) //boolean
console.log(typeof undefined) //undefined
// 对未声明的变量使用typeof操作符结果也为undefined
console.log(typeof age) //undefined
// typeof操作符无法检测null
console.log(typeof null) //object
// 从技术角度讲,函数在ECMAScript中是对象,不是一种数据类型,但是用typeof操作符区分函数是有必要的
console.log(typeof function () {}) //function
Null对象只有一个值,这个值为null,null表示一个空对象指针,所以typeof null返回值为object
三、引用类型、null检测,使用instanceof操作符
1、由于基本类型不是对象,所以使用instanceof检测基本类型时,永远返回false
console.log(5 instanceof Object) //false
2、引用类型(除基本类型之外的都是引用类型,例如Array、RegExp)
let person = new Object()
console.log(person instanceof Object) //true
let a = [1, 2, 3];
console.log(a instanceof Array) //true
console.log([] instanceof Array) //true
let d = new Date();
console.log(d instanceof Date) //true
let a = null
console.log(a instanceof Object) //false
console.log(typeof a) //object
四、Object.prototype.toString方法(apply,call都可以)
console.log(Object.prototype.toString.apply('')) // [object String]
console.log(Object.prototype.toString.apply(1)) // [object Number]
console.log(Object.prototype.toString.apply(true)) // [object Boolean]
console.log(Object.prototype.toString.apply(Symbol())) //[object Symbol]
console.log(Object.prototype.toString.apply(undefined)) // [object Undefined]
console.log(Object.prototype.toString.apply(null)) // [object Null]
console.log(Object.prototype.toString.apply(new Function())) // [object Function]
console.log(Object.prototype.toString.apply(new Date())) // [object Date]
console.log(Object.prototype.toString.apply([])) // [object Array]
console.log(Object.prototype.toString.apply(new RegExp())) // [object RegExp]
console.log(Object.prototype.toString.apply(new Error())) // [object Error]
console.log(Object.prototype.toString.apply(document)) // [object HTMLDocument]
console.log(Object.prototype.toString.apply(window)) //[object global] window 是全局对象 global 的引用