js判断数据类型的三种方法(文章最后有快捷方法哦!)

js判断数据类型的方法有很多种,本文只选择三种使用频率较高的方法来说明,这里比较推崇使用第三种方法,闲话少说下面开始介绍:

1、typeof

typeof new String( 'bart' ); // object
typeof 'bart'; // string
typeof 10; // number
typeof true; // boolean
typeof null; // object  ->  这是bug,但永远不会修复,所以我们注意就行了!
typeof undefined; // undefined

大家可能注意到了前两行都是字符串,但是为什么返回的一个是 string 一个是 object 呢?这是因为虽然都是字符串,但是创建方式和存储方式不一样,一个是堆内存,一个是栈内存,所以导致了这种特殊性,这里不做过多介绍,只是说明使用 typeof 进行数据类型判断需要注意的情况( 你不这样写,不代表你的团队好基友不会这样写? ),有兴趣可以自行查阅堆内存和栈内存的区别。

2、instanceof

判断对象A是否为对象B的实例
// 这里小小封装一下,小小的解释一下:
// isInstanceof 封装了一下 instanceof 方法,调用时传入两个参数
如果第一个参数的原型是第二个参数,那么返回 true,否则返回 false

let isInstance = function( A, B ) {
	return A instanceof B
}isInstance( new Number( 10 ), Number ); // true
isInstance( new String( 'bart' ), String ); // true
isInstance( new Boolean( false ), Boolean ); // true
isInstance( {}, Object ); // true

3、toString

Object.prototype.toString.call( 'bart' ); // [object String] 对比
Object.prototype.toString.call( new String( 'bart' ) ); // [object String] 对比
Object.prototype.toString.call( 10 ); // [object Number]
Object.prototype.toString.call( function(){} ); // [object Function]
Object.prototype.toString.call( { name: 'bart' } ); // [object Object]
Object.prototype.toString.call( Symbol() ); // [object Symbol]
Object.prototype.toString.call( new Date() ); // [object Date]
Object.prototype.toString.call( [ 1, 2, 3 ] ); // [object Array]

大家发现我标记的前两行,两种创建字符串的方式都可以精确地判断出来为 [object String] ,但是这样使用起来代码很多,而且可读性很差,所以这里借鉴 《JavaScript设计模式与开发实践》 的部分代码并小小改动提供两种封装使用 toString 的模式

① 把借用 Object.prototype.toString 的过程封装起来

let isType = function( type ) {
	return function( obj ) {
		return Object.prototype.toString.call( obj ) === `[object ${type}]`
	}
};

let isString = isType( 'String' );
isString( 'bart' ); // true
isString( new String( 'bart' ) ); // true

② 使用循环注册要使用的方法

let Type = {};
let registerType = [ 'String', 'Number', 'Array' ]; // 注册使用哪种类型直接写到这个数组里就可以了

for ( let i = 0, type; type = registerType[i++]; ) {
	(function( type ){
		Type[ `is${type}` ] = function( obj ) {
			return Object.prototype.toString.call( obj ) === `[object ${type}]`;
		}
	})( type );
};

Type.isString( 'bart' ); // true
Type.isString( new String( 'bart' ) ); // true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值