一、數組的深淺拷貝
數組的複製,是地址賦值,如下
var arr = ["One","Two","Three"];
var arrto = arr;
arrto[1] = "test";
document.writeln("數組的原始值:" + arr + "<br />");//Export:數組的原始值:One,test,Three
document.writeln("數組的新值:" + arrto + "<br />");//Export:數組的新值:One,test,Three
這並不是我們想要的結果
以下只能一維數組複製!!!!
方法一:js的slice函數
var arr = ["One","Two","Three"];
var arrtoo = arr.slice(0);
arrtoo[1] = "set Map";
document.writeln("數組的原始值:" + arr + "<br />");//Export:數組的原始值:One,Two,Three
document.writeln("數組的新值:" + arrtoo + "<br />");//Export:數組的新值:One,set Map,Three
方法二:js的concat方法
var arr = ["One","Two","Three"];
var arrtooo = arr.concat();
arrtooo[1] = "set Map To";
document.writeln("數組的原始值:" + arr + "<br />");//Export:數組的原始值:One,Two,Three
document.writeln("數組的新值:" + arrtooo + "<br />");//Export:數組的新值:One,set Map To,Three
二:對象的深淺拷貝
var cloneObj = function(obj){
var str, newobj = obj.constructor === Array ? [] : {};
if(typeof obj !== 'object'){
return;
} else if(window.JSON){
str = JSON.stringify(obj), //系列化對象
newobj = JSON.parse(str); //還原
} else {
for(var i in obj){
newobj[i] = typeof obj[i] === 'object' ?
cloneObj(obj[i]) : obj[i];
}
}
return newobj;
};