var arr1 = ['red','green']; var arr2 = arr1.slice(0);//复制 console.log(arr2)//['red','green']; arr1.push('black') ;//改变color1的值 console.log(arr2)//["red", "green"] console.log(arr1)//["red", "green", "black"]
var arr1 = ['red','green']; var arr2 = arr1.concat();//复制 console.log(arr2)//['red','green']; arr1.push('black') ;//改变color1的值 console.log(arr2)//["red", "green"] console.log(arr1)//["red", "green", "black"]
深拷贝:
var arr1 = ['red','green']; var arr2 = JSON.parse(JSON.stringify(arr1));//复制 console.log(arr2)//['red','green']; arr1.push('black') ;//改变color1的值 console.log(arr2)//["red", "green"] console.log(arr1)//["red", "green", "black"]
function deepClone(obj){ //判断参数是不是一个对象 let objClone = obj instanceof Object?[]:{}; if(obj && typeof obj==="object"){ for(key in obj){ if(obj.hasOwnProperty(key)){ //判断ojb子元素是否为对象,如果是,递归复制 if(obj[key]&&typeof obj[key] ==="object"){ objClone[key] = deepClone(obj[key]); }else{ //如果不是,简单复制 objClone[key] = obj[key]; } } } } return objClone; } var a ={ x:1, y:2 }; b=deepClone(a); a.x=3 console.log(a); console.log(b);