js clone物件的方法
阿新 • • 發佈:2018-11-07
方法一:
function clone(obj){
var o;
if(typeof obj == "object"){
if(obj === null){
o = null;
}else{
if(obj instanceof Array){
o = [];
for(var i = 0, len = obj.length; i < len; i++){
o.push(clone (obj[i]));
}
}else{
o = {};
for(var k in obj){
o[k] = clone(obj[k]);
}
}
}
}else{
o = obj;
}
return o;
}
var obj1 = {name: "kitty", sex: "female" , age: 18, favorite: ["football", "sing", "dancing"]};
var obj2 = clone(obj1);
方法二:
function clone(obj){
var o, obj;
if (obj.constructor == Object){
o = new obj.constructor();
}else{
o = new obj.constructor(obj.valueOf());
}
for(var key in obj){
if ( o[key] != obj[key] ){
if ( typeof(obj[key]) == 'object' ){
o[key] = clone(obj[key]);
}else{
o[key] = obj[key];
}
}
}
o.toString = obj.toString;
o.valueOf = obj.valueOf;
return o;
}
方法三:
function clone(obj){
function Fn(){}
Fn.prototype = obj;
var o = new Fn();
for(var a in o){
if(typeof o[a] == "object") {
o[a] = clone(o[a]);
}
}
return o;
}