js如何正确判断数据类型

前言

关于js判断数据类型,我们可以使用typeof和instanceof来判断,关于typeof和instanceof的知识点,可以参考我上一篇文章前端面试题汇总之typeof和instanceof
但是,通过typeof和instanceof来判断数据类型,真的是最优选择么?

浅谈typeof的优缺点

优点:能快速检查undefined,string,number,boolean,function类型
缺点:当类型为object,null,array时都会返回object,所以不能区分这三类

console.log(typeof 1) // number
console.log(typeof true) // boolean
console.log(typeof 'str') // string
console.log(typeof undefined) // undefined
console.log(typeof null) // object
console.log(typeof function(){}) // function
console.log(typeof [1, 2, 3]) // object
console.log(typeof new Object()) // object
console.log(typeof {}) // object

浅谈instanceof的优缺点

优点:能检测array,function,object类型
缺点:检测不了number,boolean,string

console.log(1 instanceof Number) // false
console.log('str' instanceof String) // false
console.log(true instanceof Boolean) // false
console.log([1, 2, 3] instanceof Array) // true
console.log(function(){} instanceof Function) // true
console.log({} instanceof Object) // true

推荐Object.prototype.toString.call()

优点:能准确的判断所有的类型包括iframe。
缺点:不能精准判断自定义对象,对于自定义对象只会返回[object Object]

  1. 判断基本类型:(输出的值是字符串,并且用中括号括起来,左边是object(小写),右边是类型(首字母大写))
Object.prototype.toString.call(null);//”[object Null]”
Object.prototype.toString.call(undefined);//”[object Undefined]”
Object.prototype.toString.call(“abc”);//”[object String]”
Object.prototype.toString.call(123);//”[object Number]”
Object.prototype.toString.call(true);//”[object Boolean]”
  1. 判断原生引用类型:
函数类型
Function fn(){console.log(“test”);}
Object.prototype.toString.call(fn);//”[object Function]”
日期类型
var date = new Date();
Object.prototype.toString.call(date);//”[object Date]”
数组类型
var arr = [1,2,3];
Object.prototype.toString.call(arr);//”[object Array]”
正则表达式
var reg = /[hbc]at/gi;
Object.prototype.toString.call(arr);//”[object Array]”
自定义类型
function Person(name, age) {
    this.name = name;
    this.age = age;
}
var person = new Person("Rose", 18);
Object.prototype.toString.call(arr); //”[object Object]”
**很明显这种方法不能准确判断person是Person类的实例,而只能用instanceof 操作符来进行判断,如下所示:
console.log(person instanceof Person);//输出结果为true**
  1. 判断原生JSON对象:
var isNativeJSON = window.JSON && Object.prototype.toString.call(JSON);
console.log(isNativeJSON);//输出结果为”[object JSON]”说明JSON是原生的,否则不是;
注意:Object.prototype.toString()本身是允许被修改的,而我们目前所讨论的关于Object.prototype.toString()这个方法的应用都是假设toString()方法未被修改为前提的。

参考:
https://www.jianshu.com/p/d95c8a7d8d5e
https://cloud.tencent.com/developer/article/1508145
https://www.cnblogs.com/feifei0928/p/12185083.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值