利用jquery 的extend方法:
extend([param1,]obj1,obj2);
说明:1.>将对象obj2复制到obj1中
2>param1,为布尔类型,true 表示深度复制
eg:
eg:
- var object1 = {
- apple: 0,
- banana: {weight: 52, price: 100},
- cherry: 97
- };
- var object2 = {
- banana: {price: 200},
- durian: 100
- };
- $.extend(true,object1, object2);//深度复制,要复制以个新对象,可将object1写成{}
- object2.banana.price=100;//修改值
- alert(object1.banana.price)//深度复制,object1中的值没有改变
javascript 实现:
- function cloneObject(obj) {
- var clone = {};
- for(var i in obj) {
- if(typeof(obj[i])=="object")
- clone[i] = cloneObject(obj[i]);
- else
- clone[i] = obj[i];
- }
- return clone;
- }
eg:
- function cloneObject(obj) {
- var clone = {};
- for(var i in obj) {
- if(typeof(obj[i])=="object")
- var object1 = {
- apple: 0,
- banana: {weight: 52, price: 100},
- cherry: 97
- };
- var obj= cloneObject(object1 );
- object2.banana.price=200;//修改值
- alert( obj.banana.price )//仍然输出100