js對象的比較

項目中需要比較兩個對象是否相等,給Object對象開展了(別緊張,別說我把它污染了),一個實現而已,象java一樣可以只給自己想要的類重寫equals方法。

Object.prototype.equals = function(obj){
	if(this == obj) 
		return true;
	if(typeof(obj)=="undefined"||obj==null||typeof(obj)!="object") 
		return false;
	var length = 0; var length1=0;
	for(var ele in this) {
		length++;
	}				
	for(var ele in obj) {
		length1++;
	}				
	if(length!=length1) 
		return false;
	if(obj.constructor==this.constructor){
		for(var ele in this){
			if(typeof(this[ele])=="object") {
				if(!this[ele].equals(obj[ele]))
					return false;
			}
			else if(typeof(this[ele])=="function"){
				if(!this[ele].toString().equals(obj[ele].toString())) 
					return false;
			}
			else if(this[ele]!=obj[ele]) 
				return false;
		}
		return true;
	}
	return false;
};

示例如下:

var p1 = {name:"jack",age:18}; 
var p2 = {name:"lucy",age:10}; 
var p3 = {name:"jack",age:18}; 


console.log(p1.equals(p2));//false 
console.log(p1.equals(p3));//true 
console.log(p1.equals({name:"jack",age:18}));//true

posted on 2011-02-26 09:34  snandy  阅读(2704)  评论(1编辑  收藏  举报