JS Object compare
需求:
比较两个Object, 比如:
var obj1=new Object();
obj1.prop1="p1";
obj1.prop2="p2";
var obj2=new Object();
obj2.prop1="p1";
obj2.prop2="p2";
方法:
1. 用 Object.toJSON method(
If you are using a JSON library, you can encode each object as JSON, then compare the resulting strings for equality.
)
Syntax:
Object.toJSON(obj);
Return Value :
Returns a JSON string.
code:
<html>
<head>
<title>Prototype examples</title>
<script type="text/javascript"
src="/javascript/prototype.js">
</script>
<script>
function showResult(){
var o = {name: 'Prototype', Version: 1.6};
var obj1=new Object();
obj1.prop1=2;
obj1.prop2="p2";
alert("Object.toJSON(o): " + Object.toJSON(o));
}
</script>
</head>
<body>
<p>Click the button to see the result.</p>
<br />
<br />
<input type="button" value="Result" onclick="showResult();"/>
</body>
</html>
var eq =Object.toJSON(obj1)==Object.toJSON(obj2);
alert(eq);
2. use Object.prototype
Object.prototype.equals =function(iObj){
if(this.constructor !== iObj.constructor)
returnfalse;
var aMemberCount =0;
for(var a inthis){
if(!this.hasOwnProperty(a))
continue;
if(typeofthis[a]==='object'&&typeof iObj[a]==='object'?!this[a].equals(iObj[a]):this[a]!== iObj[a])
returnfalse;
++aMemberCount;
}
for(var a in iObj)
if(iObj.hasOwnProperty(a))
--aMemberCount;
return aMemberCount ?false:true;
}
3.
function objectEquals(obj1, obj2){
for(var i in obj1){
if(obj1.hasOwnProperty(i)){
if(!obj2.hasOwnProperty(i))returnfalse;
if(obj1[i]!= obj2[i])returnfalse;
}
}
for(var i in obj2){
if(obj2.hasOwnProperty(i)){
if(!obj1.hasOwnProperty(i))returnfalse;
if(obj1[i]!= obj2[i])returnfalse;
}
}
returntrue;
}
4.
Object.equals =function( x, y ){
if( x === y )returntrue;
// if both x and y are null or undefined and exactly the same
if(!( x instanceofObject)||!( y instanceofObject))returnfalse;
// if they are not strictly equal, they both need to be Objects
if( x.constructor !== y.constructor )returnfalse;
// they must have the exact same prototype chain, the closest we can do is
// test there constructor.
for(var p in x ){
if(! x.hasOwnProperty( p ))continue;
// other properties were tested using x.constructor === y.constructor
if(! y.hasOwnProperty( p ))returnfalse;
// allows to compare x[ p ] and y[ p ] when set to undefined
if( x[ p ]=== y[ p ])continue;
// if they have the same strict value or identity then they are equal
if(typeof( x[ p ])!=="object")returnfalse;
// Numbers, Strings, Functions, Booleans must be strictly equal
if(!Object.equals( x[ p ], y[ p ]))returnfalse;
// Objects and Arrays must be tested recursively
}
for( p in y ){
if( y.hasOwnProperty( p )&&! x.hasOwnProperty( p ))returnfalse;
// allows x[ p ] to be set to undefined
}
returntrue;
}