- 在工作过程中有时需要判断区分数组和对象形式的数据, 直接用 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