javascript簡單實現深淺拷貝
阿新 • • 發佈:2020-08-24
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);