js typeof

function compare(a,b){
var
pt = /undefined|number|string|boolean/,
fn = /^(function\s*)(\w*\b)/,
cr = "constructor",
cn = "childNodes",
pn = "parentNode",
ce = arguments.callee;
if(pt.test(typeof a) || pt.test(typeof b) || a === null || b === null){
return a === b || (isNaN(a) && isNaN(b)); //为了方便,此处假定NaN == NaN
}
if(a[cr] !== b[cr]){
return false;
}
switch(a[cr]){
case Date : {
return a.valueOf() === b.valueOf();
};
case Function : {
return a.toString().replace(fn,'$1') === b.toString().replace(fn,'$1'); //硬编码中声明函数的方式会影响到toString的结果,因此用正则进行格式化
};
case Array : {
if(a.length !== b.length){
return false;
}
for(var i=0;i<a.length;i++){
if(!ce(a[i],b[i])){
return false;
}
}
break;
};
default : {
var alen = 0, blen = 0, d;
if(a === b){
return true;
}
if(a[cn] || a[pn] || b[cn] || b[pn]){
return a === b;
}
for(d in a){
alen++ ;
}
for(d in b){
blen++;
}
if(alen !== blen){
return false;
}
for(d in a){
if(!ce(a[d],b[d])){
return false;
}
}
break;
};
}
return true;
}
console.log(compare({},{a:1})); //false
console.log(compare({a:1},{b:2})); //false
console.log(compare({b:2,a:1},{a:1,b:2})); //true
console.log(compare({a:function(){return false;},b:2},{a:function(){return false;},b:2})); //true
console.log(compare([],[])); //true
console.log(compare([2,1],[1,2])); //false
console.log(compare(function(){alert(1)},function(){})); //false
console.log(compare(function aaa(){alert(1)},function(){alert(1)})); //true
console.log(compare(document.getElementsByTagName("a")[0],document.getElementsByTagName("a")[1])); //false
console.log(compare(document.getElementsByTagName("a")[0],document.getElementsByTagName("a")[0])); //true
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值