首页 > Web开发 > 详细

ES6结合正则判断js数据类型

时间:2020-05-27 13:19:10      阅读:40      评论:0      收藏:0      [点我收藏+]

ES5:(有重复问题)

typeof 1           ---> number
typeof hello     ---> string
typeof alert       ---> function
typeof [1,2,3]     ---> object
typeof {a:1,b:2}   ---> object
typeof null        ---> object
typeof NaN         ---> number
typeof undefined   ---> undefined
typeof Symbol()    ---> symbol

ES6: (修补了问题)

console.log(Object.prototype.toString.call("hello"));//[object String]
console.log(Object.prototype.toString.call(123));//[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({name: "jerry"}));//[object Object]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call([]));//[object Array]
console.log(Object.prototype.toString.call(new Date));//[object Date]
console.log(Object.prototype.toString.call(/\d/));//[object RegExp]
function foo(){}
console.log(Object.prototype.toString.call(new foo()));//[object Object]

 

最后ES6结合正则的方式,使用最方便:

const isType = type =>(/^\[object\s(.*)\]$/.exec(Object.prototype.toString.call(type)))[1];
isType({}) // ‘Object‘
isType([]) // ‘Array‘

注意首字母是大写

 

 

 

 

.

ES6结合正则判断js数据类型

原文:https://www.cnblogs.com/xiangsj/p/12971623.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!