JS的5种数据类型判断方法及原理超详解

首先,js的数据类型包括(ES5):

  • 基本类型:number、string、boolean、null、undefined
  • 引用类型:object、array、function、date、RegExp

1. typeof

typeof操作符返回一个字符串,可以用来判断数据所属的基本类型(null除外),但引用类型的判断结果都为object(function除外)

console.log(typeof 1);//number
console.log(typeof '1,2');//string
console.log(typeof false);//boolean
console.log(typeof undefined);//undefined
console.log(typeof null);//object
console.log(typeof [1,2]);//object
console.log(typeof {name: 'tom'});//object
console.log(typeof function(){});//function
console.log(typeof new Date());//object
  • 注意 typeof NaN === 'number'

从逻辑角度来看,null 值表示一个空对象指针,而这也正是使用 typeof 操作符检测 null 值时会返回object的原因。(引用自红宝书3.4.3节)

因此,如果定义的变量准备在将来用于保存对象,那么最好将该变量初始化为 null 而不是其他值。这样一来,只要直接检查 null 值就可以知道相应的变量是否已经保存了一个对象的引用。

var car = null; 
......//执行某些操作
if (car != null) {
     // 对 car 对象执行某些操作
}
  • 实际上,undefined 值是派生自 null 值的,因此 ECMA-262规定对它们的相等性测试要返回 true
console.log(null == undefined);//true

2. instanceof

  • 判断原理

instanceof 运算符用于判断构造函数的 prototype 属性是否出现在某个实例对象的原型链上,举例来说:

var Fun = function(){};
var fn = new Fun();
console.log(fn instanceof Fun);//true
console.log(fn instanceof Object);//true

也就是说当使用instanceof进行类型判断时,会在fn的原型链中向上查找,直到找到构造函数.prototype,如果找到了,就会返回true,否则返回false

回到例子上来看,正是因为:(原型链详解)

fn.__proto__ == Fun.prototype
fn.__proto__.__proto__ == Object.prototype
//因为Fun.prototype为普通对象,因此Fun.prototype.__proto__ == Object.prototype

但是再仔细想会发现

var str='test';
console.log(str.__proto__ === String.prototype);//true
console.log(str instanceof String);//false

这与上面说得相矛盾了,明明在str得原型链上找到了String.prototype,但是为什么判断结果是false呢?

这是因为你分不清字符串字面量和 String 对象,例如,当执行 'hello'.length 时,发现返回 5,但此时 'hello' 只是一个字符串字面量,之所以它会有 String 对象的属性,是由于 JS 在执行到这条语句的时候,内部将 'hello' 包装成了一个 String 对象,执行完后,再把这个对象丢弃了,这种语法叫做 “装箱”(numbe和boolean类型的字面量都是属于这种情况)。

因此回到例子上来看,当执行str.__proto__时,这里得str是JS包装后的str,因此结果为true,当判断完成后丢弃;再执行str instanceof String时,这里的str只是普通的字面量,而不是String的实例,因此结果为false

  • 应用举例
console.log(undefined instanceof undefined);//Undefined is not defined
console.log(null instanceof Null);//Null is not defined
console.log(1 instanceof Number);//false
console.log('1' instanceof String);//false
console.log(true instanceof Boolean);//false
console.log([1] instanceof Array);//true
console.log(function(){} instanceof Function);//true
console.log({name:"tom"} instanceof Object);//true
  • 可以发现,用instanceof判断1、'1'、true时不是我们想要的结果,这是因为这三个是通过字面量的方式创建的,而不是对应构造函数的实例化对象,因此不能通过instanceof判断,当下面这种方式就可以了。
console.log(new Number(1) instanceof Number);//true
console.log(new String(1) instanceof String);//true
console.log(new Boolean(true) instanceof Boolean);//true
  • undefinednull是比较特殊的,不能通过instanceof进行类型判断,这属于js的历史遗留问题,只要记住就好了。

3. constructor

  • 判断原理: 通过constructor属性
var str='i am string';//原始数据类型
console.log(str.constructor == String);//true

前面说到,str是JS包装过的,相当于JS内部执行了str = new String('i am string'),因此,此时的str的构造函数为String,判断结果为true

  • 应用举例:
var unde = undefined
var nul = null
var num = 1
console.log(unde.constructor == undefined);//Cannot read property 'constructor' of undefined
console.log(nul.constructor == Null);//Cannot read property 'constructor' of null
console.log(num.constructor == Number);//true
console.log('1'.constructor == String);//true
console.log(true.constructor == Boolean);//true
console.log([1].constructor == Array);//true
console.log(function(){}.constructor == Function);//true
console.log({name:"tom"}.constructor == Object);//true

可见,除了undefinednull,其他的类型都可以通过constructor判断出我们期望的类型结果。

  • 但是它有一点需要注意,就是,当修改constructor后,类型也会被改变
var Fn = function(){}
Fn.prototype = new String()
var fn = new Fn();
console.log(fn.constructor == String);//true
console.log(fn.constructor == Fn);//false
console.log(fn instanceof Fn);//true
console.log(fn instanceof String);//true

可以看出,当修改构造函数的原型后,instanceof判断出的结果仍是Fn,但constructor判断结果不是Fn,而是String,这不是我们期待的。

具体分析一下,首先我们知道

fn.constructor == Fn.prototype.constructor == Fn
fn.__proto__  == Fn.prototype

而此时将Fn.prototype修改为String的实例化对象,因此

fn.constructor == Fn.prototype.constructor == String
Fn.prototype.__proto__ == String.prorotype

所以,constructor判断FnString类型,instanceof判断为既是String类型,又是Fn

4. Object.prototype.toString.call(obj)

  • 判断原理

toString是Object的一个方法,会返回反映这个对象的字符串。
JS中所有的构造器Number,Array,Function等都会继承并重写这个方法。

console.log('1'.toString());//'1'
console.log([1].toString());//'1'
delete Array.prototype.toString;//删掉array继承的toString方法,就会去构造函数,也就是Object中去找
console.log([1].toString());//[object Array]

因此,直接通过Object.prototype调用这个方法,就可以准确的判断出所属类型。

  • 应用举例
console.log(Object.prototype.toString.call('1'));// [object String]
console.log(Object.prototype.toString.call(1);// [object Number]
console.log(Object.prototype.toString.call(true);// [object Boolean]
console.log(Object.prototype.toString.call(undefined);// [object Undefined]
console.log(Object.prototype.toString.call(null);// [object Null]
console.log(Object.prototype.toString.call(function(){});// [object Function]
console.log(Object.prototype.toString.call(new Date());// [object Date]
console.log(Object.prototype.toString.call([1]);// [object Array]
console.log(Object.prototype.toString.call(new RegExp());// [object RegExp]

可以看到,通过这种方法可以准确的判断出所有的类型。

5. 其他方法

除了上面四种外,有一些方法可以判断具体是否为某种特定的数据类型。

  • Array.isArray(obj):判断是否为数组
console.log(Array.isArray([1,2]));//true
console.log(Array.isArray('1,2'));//false
  • isNaN:判断是否非数值
console.log(isNaN([1,2]));//true,即非数值
console.log(isNaN('1,2'));//true,即非数值
console.log(isNaN(12));//false,即为数值
  • 16
    点赞
  • 74
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值