文享日志

判断对象类型的几种写法

JavaScript

发表于2017年10月06日22:03:47

0条评论 189次阅读

函数实现的其实并不好,因为挂载到全局变量上了。但函数凸出了一些实现方式。。

var isNumber = function(obj){
	var obj = +obj ;
	return typeof obj === 'number'&&!isNaN(obj);
}

var isSmall = function(obj){
	var temp = typeof obj === 'string'&&obj.toLowerCase();
	return temp === obj ;
}

var isLarge = function(obj){
	var temp = typeof obj === 'string'&&obj.toUpperCase();
	return temp === obj ;
}

var isChar = function(obj){
	return typeof obj === 'string'&&/[\u4E00-\u9FA5]/g.test(obj);
}

var obj_value = function(obj){
	var values = [];
	for(key in obj){
		if(hasOwnProperty.call(obj,key)){
			values.push(obj[key]);
		}
	}
	return values ;
}


var test = {
	a : 'a',
	b : 2 ,
	c : 'C' ,
	d : '韩'
}

function find(obj){
	var getValue = obj_value(obj);
	var length = getValue.length ;
	var isNum = [] , isSmal = [], isLarg = [] , isCha = [] , isNull = [];
	for(var i = 0 ; i < length ; i++){
		isNumber(getValue[i])?isNum.push(getValue[i]):isChar(getValue[i])?isCha.push(getValue[i]):isSmall(getValue[i])?isSmal.push(getValue[i]):isLarge(getValue[i])?isLarg.push(getValue[i]):isNull.push(getValue);
	}
	return {
		isNumber : isNum ,
		isChar : isCha ,
		isSamll : isSmal ,
		isLarge : isLarg ,
		isNull : isNull
	}
}

// console.log(find(test));

//正则表达式写法
var Regitem = ['\\d','[\\u4E00-\\u9FA5]','[a-z]','[A-Z]'];
var fun_item = ['obj_isNumber','obj_isChar','obj_isSmall','obj_isLarge'];

function goFunc(){
	for(var i = 0 ; i < fun_item.length ; i++){
		window[fun_item[i]] =  function(obj){
				return new RegExp(Regitem[i],'g').test(obj);
		}	
	}
}
goFunc();



//用Object.prototype.toString判断
var item = ['Number','String','Arguments'];
var goFunct = function(){
	for(var i = 0 ; i < item.length ; i++)
		window['objIs'+item[i]] = function(obj){
			return Object.prototype.toString.call(obj) === '[object '+item[i]+']'
		}
}
goFunct();


👍 0  👎 0
共有0条评论

发表新评论

提交

广告展示

腾讯云推广 阿里云推广