<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js的对象交换/复制/比较</title>
<input type="button" name="c1" value="交换对象" onclick="changeObject();" />
<input type="button" name="c1" value="在数组中交换对象元素" onclick="changeObject2();" />
<input type="button" name="c2" value="复制/比较对象" onclick="test();" />
<script>
function changeObject() {
var a = {name:"张三",sex:"男",data:[{age:10,weight:40},{age:5,weight:20}]};
var b = [{data:"要提交的数据",method:"POST",id:[0,1,2,3,4,5]},["abc",{type:"new"}],null];
alert("交换后\na.data[1].weight="+a.data[1].weight+"\nb[0].id[3]="+b[0].id[3]+"\nb[1][1].type="+b[1][1].type);
var c = a;
a = b;
b = c;
alert("交换后\nb.data[1].weight="+b.data[1].weight+"\na[0].id[3]="+a[0].id[3]+"\na[1][1].type="+a[1][1].type);
a[0].id[3] = 333;
a[1][1].type = "old";
b.data[1].weight = 1000;
alert("修改部分数据后\nb.data[1].weight="+b.data[1].weight+"\na[0].id[3]="+a[0].id[3]+"\na[1][1].type="+a[1][1].type);
}
function changeObject2() {
var arr = [];
arr[0] = {name:"张三",sex:"男",data:[{age:10,weight:40},{age:5,weight:20}]};
arr[1] = [{data:"要提交的数据",method:"POST",id:[0,1,2,3,4,5]},["abc",{type:"new"}],null];
alert("交换后\narr[0].data[1].weight="+arr[0].data[1].weight+"\narr[1][0].id[3]="+arr[1][0].id[3]+"\narr[1][1][1].type="+arr[1][1][1].type);
var tmp = arr[0];
arr[0] = arr[1];
arr[1] = tmp;
alert("交换后\narr[1].data[1].weight="+arr[1].data[1].weight+"\narr[0][0].id[3]="+arr[0][0].id[3]+"\narr[0][1][1].type="+arr[0][1][1].type);
arr[0][0].id[3] = 333;
arr[0][1][1].type = "old";
arr[1].data[1].weight = 1000;
alert("修改部分数据后\narr[1].data[1].weight="+arr[1].data[1].weight+"\narr[0][0].id[3]="+arr[0][0].id[3]+"\narr[0][1][1].type="+arr[0][1][1].type);
}
function test() {
var a = {name:"张三",sex:"男",data:[{age:10,weight:40},{age:5,weight:20}]};
var b = cloneObject(a);
alert("克隆后,\na.data[0].age="+a.data[0].age +"\nb.data[0].age="+b.data[0].age);
if (compObject(a,b)) {
alert("现在a等于b");
} else {
alert("现在a不等于b!");
}
a.data[0].age = 9;
alert("改变a.data[0].age为"+a.data[0].age +"\nb.data[0].age="+b.data[0].age);
if (compObject(a,b)) {
alert("现在a等于b");
} else {
alert("现在a不等于b!");
}
}
function cloneObject(o) {
//克隆对象
if(typeof(o) != "object") return o;
if(o == null) return o;
var n = (o.constructor == Array) ? [] : {};
for(var i in o) n[i] = cloneObject(o[i]);
return n;
}
function compObject(o,o2){
//对比对象
if(o == o2) {return true;}
if(typeof(o)=="undefined"||o==null||typeof(o)!="object"){return false;}
if(typeof(o2)=="undefined"||o2==null||typeof(o2)!="object"){return false;}
var l = 0;
var l2=0;
for(var i in o) {
l++;
}
for(var i in o2) {
l2++;
}
if(l!=l2) {return false;}
if(o.constructor == o2.constructor){
for(var i in o){
if(typeof(o[i])=="object") {
if(!compObject(o[i],o2[i]))
return false;
}else if(o[i]!=o2[i]) {
return false;
}
}
return true;
}
return false;
};
</script>
</BODY>
|