JS类型检测

一、数据类型分类

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 的引用

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值