Js几种数据类型检测的方法

前言:

最近在做一个项目,碰到一些需要进行数据类型判断的地方,索性就总结一下所有JS检测类型的方法。

先介绍一下JS的数据类型

JS分基础数据类型复杂数据类型,也叫引用数据类型

基础数据类型:
Sting Number Boolean Null Undefined ,以及es6新增的一个Symbol

复杂数据类型:
Object 其中包括 Arry,Function,RegExp,Date

判断方法:

  1. typeof
  2. instanceof
  3. constructor
  4. Object.prototype.toString.call(obj)

用法

typeof
typeof用来检测基础类型 ,返回类型的字符串

  //字符串
  typeof 'leon'  // 'sting'
  
  //整数
  typeof 22  // 'number'
  
  //undefined
  typeof undefined  // 'undefined'
  
  //Boolean
  typeof true  // 'boolean'
  
  //Null
  typeof null  // 'object' 这为什么是object ?
  // 因为null表示的是一个空指针,指针表示的是引用型数据,所以返回object
  
  //Object
  typeof [1,2.3]      //'object' 
  typeof {a: 'ww'}    //'object' 
  typeof new Date()   //'object' 
  
  //function
  typeof function(){}     //"function"

instanceof

instanceof 用来检测复杂类型,返回boolean,但是不能检测Null

// 这种检测方式一般不常用
[1, 2] instanceof Array  //true

({a: 1}) instanceof Object  //true

(function(){}) instanceof Function  //true

Constructor
返回结果为构造器,也可以检测自定义类型;

但是不适用于null和undefined。

[1,2,3].constructor == Arry //true

(function(){}).constructor == Function // true

{ 'name':'aaa'}.constructor == Object // true

(1234).constructor == Number // true

(true).constructor == Boolean // true

function Leon(){}
var leon = new Leon();
leon.constructor == Leon;  // true 

Object.prototype.toString.call(obj)
这种方法是用的最多的也是最万能的,推荐使用

Object.prototype.toString.call('aaa'); //[object,String]

Object.prototype.toString.call(1); //[object,Number]

Object.prototype.toString.call(true) // [object,Boolean]

Object.prototype.toString.call([1,2,3]); //"[object Array]"

Object.prototype.toString.call({name:'leon'}); //"[object Object]"

Object.prototype.toString.call(function(){}); //"[object Function]"

Object.prototype.toString.call(null); //"[object Null]"

Object.prototype.toString.call(undefined); //"[object Undefined]"
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值