一、简单数据类型
浅拷贝:newArr = arr
// 简单的赋值
var arr = [1,2,3,4];
var newArr = arr;
newArr.push(5)
console.log(arr);//[1,2,3,4,5]
深拷贝:newArr
<script>
// 浅拷贝:指向的是堆内存的通风一个对象
//深拷贝:指向堆内存的不同对象
1、扩展
var arr = [1,2,3,4];
var newArr = [...arr];
newArr.push(5)
console.log(arr);//[1,2,3,4]
2、slice
var arr = [1,2,3,4];
var newArr = arr.slice(0,);
arr.push(5)
console.log(arr);//[1,2,3,4]
3、concat
var arr = [1,2,3,4]
var newArr = [].concat(arr)
newArr.push(5);
console.log(arr);//[1,2,3,4]
</script>
二、复杂数据类型
//浅拷贝
<script>
var arr = [{name:"lisi"},{name:"wangwu"}]
var newArr = [...arr]
arr[0].name = "react";
console.log(arr);
</script>
JSON.parse JSON.stringify实现
//深拷贝 JSON.parse JSON.stringify
<script>
var arr = [{name:"lisi"},{name:"wangwu"}];
var newArr = JSON.parse(JSON.stringify(arr));
arr[0].name = "react"
console.log(newArr);
</script>
算法实现
<script>
var arr = [{name:"lisi"},{name:"wangwu"}];
function deepClone(obj){
//如果是初始值 直接返回
let result;
if(obj instanceof Array){
result = []
}else if(typeof obj =="object"){
result = {}
}else{
return obj
}
for(let key in obj){
result[key] = deepClone(obj[key])
}
return result
}
var newArr = deepClone(arr)
arr[0].name = "react"
console.log(newArr);
</script>