文章目录
前话
-
JS中的数据类型
- 1.基本数据类型:null undefined boolean number string
- 2.复杂数据类型:object(具体包含了function array data等) symbol(ES6)
-
常用的数据类型判断方法有:typeof instanceof Object.prototype.toString constructor
使用typeof判断数据类型
使用typeof判断基本数据类型
- 返回数据类型的
字符串
console.log(typeof 5) // 'number'
console.log(typeof 'zsy') // 'string'
console.log(typeof undefined) // 'undefined'
console.log(typeof true) // 'boolean'
console.log(typeof null) // 注意这里:'object'
使用typeof判断复杂数据类型
const foo = () => 1
console.log(typeof foo) // 'function'
const foo1 = {}
console.log(typeof foo1) // 'object'
const foo2 = []
console.log(typeof foo2) // 'object'
const foo3 = new Date()
console.log(typeof foo3) // 'object'
const foo4 = Symbol('name')
console.log(typeof foo4) // 'symbol'
使用instanceof判断数据类型
- a instanceof B 判断的是,a是否为B的实例,即a的原型链上是否存在B的构造函数
function Person(name){
this.name = name
}
let p = new Person('zsy')
console.log(p instanceof Person) // true
// 顺着p的原型链能找到Object的构造函数,即如下代码:
console.log(p.__proto__.__proto__ === Object.prototype) // true
- 注意如下:
console.log(5 instanceof Number) // false,因为5是基本数据类型,不是Number构造函数构造出来的实例对象,可以改为如下:
console.log(new Number(5) instanceof Number) // true
// class 本质上是函数,可见class是语法糖
class People {}
console.log(typeof People) // 'function'
使用Object.prototype.toString判断数据类型
- 万能方法
console.log(Object.prototype.toString.call(1)) // [object Number]
console.log(Object.prototype.toString.call('zsy')) // [object String]
console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
console.log(Object.prototype.toString.call({})) // [object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
console.log(Object.prototype.toString.call(function () {})) // [object Function]
console.log(Object.prototype.toString.call(null)) // [object Null]
console.log(Object.prototype.toString.call(Symbol('name'))) // [object Symbol]
使用constructor判断数据类型
var foo = 5
console.log(foo.constructor) // [Function: Number]
var foo1 = 'zsy'
console.log(foo1.constructor) // [Function: String]
var foo2 = true
console.log(foo2.constructor) // [Function: Boolean]
var foo4 = []
console.log(foo4.constructor) // [Function: Array]
var foo5 = {}
console.log(foo5.constructor) // [Function: Object]
var foo6 = () => {}
console.log(foo6.constructor) // [Function: Function]
var foo7 = new Date()
console.log(foo7.constructor) // [Function: Date]
var foo8 = Symbol('name')
console.log(foo8.constructor) // [Function: Symbol]
var foo9 = undefined
console.log(foo9.constructor) // Cannot read properties of undefined (reading 'constructor')
var foo10 = null
// console.log(foo10.constructor) // Cannot read properties of null (reading 'constructor')