转载自:http://hi.baidu.com/lmh2072005/item/565af845e94cba38fa8960c9
javascript对象深层复制
其实看到网上一个更新简单的方法 当是json对象时 直接先把json对象转换为json字符串
然后复制该字符串后再把复制的字符串 转为json对象
var a = jsonObj;
var b = JSON.stringify(a);
b = JSON.parse(b);
对非json对象的对象就没什么用了 还有ie6/7不支持这两个方法。
下面这个就比较全面了 无限深层copy
function deepCopy(obj){
if(obj instanceof Array){
var newObj = [],
i = obj.length;
while(i--){
newObj[i] = arguments.callee.call(null,obj[i])
}
return newObj;
}else if(obj instanceof Date){
var newDate = new Date();
newDate.setTime(obj.getTime());
return newDate;
}else if(obj instanceof Object){
var newObj = {};
for(var i in obj){
newObj[i] = arguments.callee.call(null,obj[i])
}
return newObj;
}
else{
return obj;
}
}
后来发现其实还不够完善
发现对于Function Date RegExp 类型的直接 return 就OK 了
完善后的:
function deepCopy(obj){
if(obj instanceof Array){
var arr = [],i = obj.length;
while(i--){
arr[i] = arguments.callee.call(null,obj[i]);
}
return arr;
}else if(obj instanceof Date || obj instanceof RegExp || obj instanceof Function){
return obj; //这几种类型传入的值非索引? 直接return
}else if(obj instanceof Object){
var a = {};
for(var i in obj){ //标志1
a[i] = arguments.callee.call(null,obj[i]);
}
return a;
}else{
return obj;
}
}
看了网上有些要在标志1处加个判断是否是自己的属性 obj.hasOwnProperty(i)
觉得不要加这个判断 因为既然是deepCopy 继承的属性应该也要复制的 。
下面是测试用例:
var aClass=function(name){
this.name = name;
};
aClass.prototype.fn=function(){
console.log('abc');
}
var bClass = function(age){
this.age=age;
}
bClass.prototype=aClass.prototype;
var a = {
'aa':function(s){return s+2;},
'bb':new RegExp("\\d"),
'cc':new Date('2012/01/01'),
'dd':['sdsdf',123,function(){},new Date(),true,{'aa':{'aa':[1]}}],
'ee':{'xx':function(){return 1},'ssdf':'adf'},
'ff':'asdfasf',
'gg':null,
'hh':true,
'ii':new bClass(20)
};
var b = deepCopy(a);
//输出a
console.log(a);
//复制后改变a的值
a.dd[2]=new RegExp("\\s");
a.aa=function(xx){return 20;}
a.bb='';
a.cc=new Date();
a.dd[3]=new Date('2012/01/01');
a.ee.xx=function(){return 2+1;};
a.gg={};
a.dd[5]['aa']['aa'][0]=0;
a.ff='aa';
a.hh=0;
//输出b
console.log(b);
转载自:http://www.css88.com/archives/4818
1 | var a={ "a" :1}; |
2 |
3 | var b=a; |
4 |
5 | b[ "b" ]=2; |
6 |
7 | console.log(a); //{"a":1,"b":2}; |
01 | function cloneObject(o) { |
02 | if (!o || 'object' !== typeof o) { |
03 | return o; |
04 | } |
05 | var temp; |
06 | if (o.constructor === Array){ |
07 | //temp=o.concat(); |
08 | temp = []; |
09 | var i = o.length; |
10 | while (i--) { |
11 | temp[i] = cloneObject(o[i]); |
12 | } |
13 | } else if (o.constructor === Object){ |
14 | temp = {}; |
15 | for ( var k in o) { |
16 | if (o.hasOwnProperty(k)){ |
17 | temp[k] = cloneObject(o[k]); |
18 | } |
19 | } |
20 | } |
21 | return temp; |
22 | } |
1 | function cloneObject(obj){ |
2 | var o = obj.constructor === Array ? [] : {}; |
3 | for ( var i in obj){ |
4 | if (obj.hasOwnProperty(i)){ |
5 | o[i] = typeof obj[i] === "object" ? cloneObject(obj[i]) : obj[i]; |
6 | } |
7 | } |
8 | return o; |
9 | } |