标签:
记录一个常见的面试题,javascript中对象的深度克隆,转载自:http://www.2cto.com/kf/201409/332955.html
今天就聊一下一个常见的笔试、面试题,js中对象的深度克隆。翻了下这个题目,在很多地方出现过,已经算一个老的题目了,但是每年的校招中总会考到,其实想想,这个题目考查的知识点还是蛮多的,尤其是对基础知识的考查。好了,闲话不多说,开始正题。
//数值克隆的表现 var a="1"; var b=a; b="2"; console.log(a);// "1" console.log(b);// "2"
//字符串克隆的表现 var c="1"; var d=c; d="2"; console.log(c);// "1" console.log(d);// "2"
//字符串克隆的表现 var x=true; var y=x; y=false; console.log(x);// true console.log(y);// false
从上面的代码大家可以看出,原始类型即使我们采用普通的克隆方式仍能得到正确的结果,原因就是原始类型存储的是对象的实际数据。
var m=function(){alert(1);}; var n=m; n=function(){alert(2);}; console.log(m());//1 console.log(n());//2
var oPerson={ oName:"rookiebob", oAge:"18", oAddress:{ province:"beijing" }, ofavorite:[ "swimming", {reading:"history book"} ], skill:function(){ console.log("bob is coding"); } }; function clone(obj){ var result={}; for(key in obj){ result[key]=obj[key]; } return result; } var oNew=clone(oPerson); console.log(oPerson.oAddress.province);//beijing oNew.oAddress.province="shanghai"; console.log(oPerson.oAddress.province);//shanghai
//返回传递给他的任意对象的类 function isClass(o){ if(o===null) return "Null"; if(o===undefined) return "Undefined"; return Object.prototype.toString.call(o).slice(8,-1); }
//深度克隆 function deepClone(obj){ var result,oClass=isClass(obj); //确定result的类型 if(oClass==="Object"){ result={}; }else if(oClass==="Array"){ result=[]; }else{ return obj; } for(key in obj){ var copy=obj[key]; if(isClass(copy)=="Object"){ result[key]=arguments.callee(copy);//递归调用 }else if(isClass(copy)=="Array"){ result[key]=arguments.callee(copy); }else{ result[key]=obj[key]; } } return result; } //返回传递给他的任意对象的类 function isClass(o){ if(o===null) return "Null"; if(o===undefined) return "Undefined"; return Object.prototype.toString.call(o).slice(8,-1); } var oPerson={ oName:"rookiebob", oAge:"18", oAddress:{ province:"beijing" }, ofavorite:[ "swimming", {reading:"history book"} ], skill:function(){ console.log("bob is coding"); } }; //深度克隆一个对象 var oNew=deepClone(oPerson); oNew.ofavorite[1].reading="picture"; console.log(oNew.ofavorite[1].reading);//picture console.log(oPerson.ofavorite[1].reading);//history book oNew.oAddress.province="shanghai"; console.log(oPerson.oAddress.province);//beijing console.log(oNew.oAddress.province);//shanghai
//深度克隆 function deepClone(obj){ var result={},oClass=isClass(obj); // if(oClass==="Object"){ // result={}; // }else if(oClass==="Array"){ // result=[]; // }else{ // return obj; // } for(key in obj){ var copy=obj[key]; if(isClass(copy)=="Object"){ result[key]=arguments.callee(copy); }else if(isClass(copy)=="Array"){ result[key]=arguments.callee(copy); }else{ result[key]=obj[key]; } } return result; } function isClass(o){ if(o===null) return "Null"; if(o===undefined) return "Undefined"; return Object.prototype.toString.call(o).slice(8,-1); } //克隆一个数组 var arr=["a","b","c"]; var oNew=deepClone(arr); console.log(oNew);//Object {0: "a", 1: "b", 2: "c"}
标签:
原文地址:http://www.cnblogs.com/jq-melody/p/4499333.html