精确判断数组和对象数据类型方法

  • 在工作过程中有时需要判断区分数组和对象形式的数据, 直接用 typeof 无疑会得到下面的结果:
console.log(typeof {'name': 'zhangsan'}) // 输出: object
console.log(typeof [12,1])               // 输出: object

这时候就需要更精确的判断方法了:

var isType = function( type ) {
	return function( obj ) {
		return Object.prototype.toString.call(obj) === '[object '+ type +']'
	}
}
var isArray = isType( 'Array' )
var isObject = isType( 'Object' )
var isString = isType( 'String' )
console.log( isArray([1,2,3,]) )          // 输出: true
console.log( isObject({'name': 'zs'}) )   // 输出: true
console.log( isString ('zs') )            // 输出: true

再进一步可以批量注册这些判断函数:

var Type = {}
var Arr = ['String', 'Object', 'Number', 'Array']
for (var i = 0; i < Arr.length ; i++) {
	(function(i) {
		Type['is'+ Arr[i]] = function(obj) {
			return Object.prototype.toString.call(obj) === '[object '+ Arr[i] +']'
		}
	})(i)
}
console.log( Type.isString('zs') )            // 输出: true
console.log( Type.isObject({'name':'zs'}) )   // 输出: true
console.log( Type.isNumber(12) )              // 输出: true
console.log( Type.isArray(['zs']) )           // 输出: true
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值