第一种方法
function deepClone(arg){
if(arg === null || typeof arg !== 'object'){
return arg
}
if(arg instanceof Array){
var copy= []
for(let i = 0;i<arg.length;i++){
copy.push(arg[i])
}
return copy
}
if(arg instanceof Date){
var copy = new Date()
copy.setTime(arg.getTime())
return copy
}
if(arg instanceof Object){
let copy = {}
for(let key in value){
if(arg.hasOwnProperty(key)){
copy[key] = deepClone(arg[key])
}
}
return copy
}
}
var arg = [1,2,{a:'xxx',b:['yyy',{s:1}]}]
var arr1 = deepClone(arg)
console.log(arr1==arg);
console.log(arg);
第二种方法:
function deepClone(arr){
return $.extend([], arr); //[]这里是数组方法,如果是对象深拷贝就是{}
}
var arr1= [1,[22,222],3,'jjj']
var arr2 = deepClone(arr1)
arr1.push(arr1)
console.log(deepClone(arr2));
console.log(arr1);
第三种方法:
var a = { n: {name:'whatever'} };
var b = JSON.parse( JSON.stringify(a) );