它们都是用来复制的
1. 浅拷贝(只复制引用,而未复制真正的值)
/* 简单赋值 */
var arr1 = ['a', 'b', 'c', 'd'];
var arr2 = arr1;
/* Object.assign实现的也是浅拷贝 */
var obj1 = {a:1, b:2}
var obj2 = Object.assign(obj1);
2. 深拷贝(是复制真正的值),会在堆内存中开辟新的空间
用扩展运算符实现深拷贝
缺点:这个方法只能实现第一层,当有多层的时候还是浅拷贝
/* 用扩展运算符实现深拷贝 */
var obj1 = {name: 'xxy',age: '18'
}
var obj2 = {...obj}
obj1.name = 'xy'
console.log( obj1 );
console.log( obj2 );
JSON.parse( JSON.stringify( obj3 ) )
缺点:该方法并不会拷贝内部函数
/* 用JSON.parse(JSON.stringify( obj3 ))实现深拷贝 */
<script>
var obj3 = {a: 1,b: 2,say(){console.log( 'say hello' )}
}
var obj4 = JSON.parse(JSON.stringify( obj3 ));
obj3.a = '100';
obj4.b = '咕噜咕噜';
console.log( obj3, obj4);
</script>
递归实现深拷贝
/* 写递归实现深拷贝 */
<script>
var obj2 = {a: 1,b: 2,arr: ['a','b','c','d']
}
function copyObj( obj ){if(Array.isArray(obj)){var newObj = []}else{var newObj = {};}for ( var key in obj){if( typeof obj[key] == 'object'){newObj[key] = copyObj(obj[key])}else{newObj[key] = obj[key];}}return newObj; // 此时的newObj跟前面的obj2就肯定不是同一个引用了
}
console.log( copyObj(obj2) )
</script>