一、数据类型有那些
基本类型(简单类型/值类型/原始类型):Boolean、Number、String、undefined、null、Symbol(ES6 新增)
引用类型(复杂类型):Object、Array、Function
二、 数据类型判断方法
1、typeof
typeof 返回值 “object” 、“number”、“boolean”、“undefined”、“function” 、“string”、“function”、'symbol"
typeof 返回的值都是字符串类型
typeof 操作可以判断基本类型的数据,但是也存在一些特例,比如 typeof null 返回的是“object” ,因为 从逻辑上,null 这个特殊值被认为是一个对空对象的引用,表示一个空对象指针,实际上是基础类型
typeof 5 // "number"
typeof true // "boolean"
typeof 'text' // "string"
typeof Symbol(1) // "symbol"
typeof undefined // "undefined"
typeof null // "object"
注意:因为 typeof 是一个操作符而不是函数,所以不需要参数,但是可以使用参数,执行结果是一样的
let message = "some string"
typeof message // "string"
typeof(message) // "string"
//对于引用类型的数据,typeof 判断的结果均为 “object”, 函数返回 “function” symbol 返回 ‘symbol’
typeof [] // "object"
typeof new Date() // "object"
typeof function(){} // "function"
typeof symbol("xx") // "symbol"
2、instanceof
instanceof 是用来 判断数据是否是某个对象的实例,返回一个布尔值
缺点
- 对于基本类型的数据,instanceof是不能直接判断它的类型的,因为实例是一个对象或函数创建的,是引用类型,所以需要通过基本类型对应的 包装对象 来判断。所以对于 null 和 undefined 这两个家伙就检测不了了~
5 instanceof Number // false
new Number(5) instanceof Number // true
//因为原型链继承的关系,instanceof 会把数组都识别为 Object 对象,所有引用类型的祖先都是 Object 对象
let arr = [1, 2]
console.log(Object.prototype.toString.call(arr) === '[object Array]') // true
console.log(arr instanceof Array) // true
console.log(arr instanceof Object) // true
let fn = function(){}
console.log(fn instanceof Object) // true
3、constructor
使用 constructor 可以查看目标构造函数,也可以进行数据类型判断。但是不能判断 null 和 undefined,因为这两个特殊类型没有其对应的包装对象。constructor和instanceof 类似,constructor 返回结果的是自己的构造函数,而 instructor 则是自己与构造函数比较返回布尔值
(5).constructor === Number // true
"text".constructor === String // true
true.constructor === Boolean // true
({}).constructor === Object // true
console.log({} instanceof Object) // true
// Uncaught TypeError: Cannot read property 'constructor' of undefined
undefined.constructor === undefined // 报错
null.constructor === null // 报错
4、Object.prototype.toString
在判断数据类型时,我们称 Object.prototype.toString 为 “万能方法” “终极方法”,工作中也是比较常用而且准确
// 简单实现
var arr = [1, 2, 3]
Object.prototype.toString.call(arr)
// 封装实现 (返回对应类型)
function type(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}
// 简易实现 Array.isArray() 方法
function isArray(obj) {
return type(obj) === 'array'
}
console.log(isArray(arr)) // true
在ECMAScript中,Object类型的每个实例都有 toString() 方法,返回对象的字符串表示,所以每个实例化的对象都可以调用 toString() 方法,并且其他数据类型也能使用 toString()
let obj = {a: 1}
console.log(obj.toString()) //"[object Object]"
let flag = true
console.log(flag.toString()) // "true"
let num = 1
console.log(num.toString()); // "1"
5、Array.isArray()
返回的是一个布尔值
let a = [1,2,3];
console.log(typeof a); //返回“object”
console.log(Array.isArray(a)); //true