let obj = {
str : 'abc',
num : 123,
arr : [1,2,3],
};
let obj2 = obj;
console.log(obj == obj2)//true
let obj3 = shallowCopy(obj);
function shallowCopy(source){
var target = {};
for (var key in source){
if (Object.prototype.hasOwnProperty.call(source,key)){
target[key] = source[key];
}
}
return target;
}
obj.arr[0] = [1,1,1];
obj.str = 'cde';
obj2.arr[1] = [2,2,2]
obj3.num = 3;
obj3.arr[2] = [3,3,3]
console.log(obj);
/*输出
{
str: 'cde',
num: 123,
arr: [ [ 1, 1, 1 ], [ 2, 2, 2 ], [ 3, 3, 3 ] ]
}
*/
console.log(obj2);
/*输出
{
str: 'cde',
num: 123,
arr: [ [ 1, 1, 1 ], [ 2, 2, 2 ], [ 3, 3, 3 ] ]
}
*/
console.log(obj3);
/*输出
{ str: 'abc', num: 3, arr: [ [ 1, 1, 1 ], [ 2, 2, 2 ], [ 3, 3, 3 ] ] }
*/
obj
的str
属性不会影响 obj3
,但是修改 obj3
的 arr属性(是个对象)的 arr[2],就会影响 obj的arr[2],因为arr是个对象。Object.assign
Array.prototype.slice()
, Array.prototype.concat()
var arr = ['one',1,true];
//用concat实现浅拷贝
//var arr2 = arr.concat();
//用slice实现浅拷贝
var arr2 = arr.slice();
arr2[0] = 'two';
console.log(arr);//[ 'one', 1, true ]
console.log(arr2);//[ 'two', 1, true ]
var arr = [{one: 1},[1,2,3]];
//用concat实现浅拷贝
//var arr2 = arr.concat();
//用slice实现浅拷贝
var arr2 = arr.slice();
arr2[0].one = 'two';
arr[1][0] = [4,5,6];
console.log(arr);
//[ { one: 'two' }, [ [ 4, 5, 6 ], 2, 3 ] ]
console.log(arr2);
//[ { one: 'two' }, [ [ 4, 5, 6 ], 2, 3 ] ]
var arr = ['abc',[1,2,3],true,{one:1}]
var arr2 = JSON.parse(JSON.stringify(arr));
arr[3].one = 2;
arr2[1][0] = 0;
console.log(arr);
//[ 'abc', [ 1, 2, 3 ], true, { one: 2 } ]
console.log(arr2);
//[ 'abc', [ 0, 2, 3 ], true, { one: 1 } ]
var deepCopy = function(obj){
if (typeof obj != 'object') return;
var new_obj = obj instanceof Array ? [] : {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
new_obj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
}
}
return new_obj;
}
var obj = {
str: 'abc',
num: 123,
a: {
n: 10
//flag: true
}
}
var obj2 = deepCopy(obj);
obj.str = 'cde';
obj2.a.n = 9;
console.log(obj);
//{ str: 'cde', num: 123, a: { n: 10 } }
console.log(obj2);
//{ str: 'abc', num: 123, a: { n: 9 } }
和原数据是否指向同一对象 | 第一层数据为基本数据类型 | 原数据中包含对象 | |
赋值 | 是 | 改变会使原数据一同改变 | 改变会使原数据一同改变 |
浅拷贝 | 否 | 改变不会使原数据一同改变 | 改变会使原数据一同改变 |
深拷贝 | 否 | 改变不会使原数据一同改变 | 改变不会使原数据一同改变 |
参考文章:https://mp.weixin.qq.com/s?src=11×tamp=1590028308&ver=2351&signature=HV0OEzUBVR9VT-K*OazkdG9hpUnKC1qHs4H1VdjIlWtsDuiLZkGe5oNbW79FdJi-ufb95Byver4If0k9313thFd6E3aXSYvysr3W2SzcR0o*Oljo7ShCmojAhL1pPPuu&new=1
https://mp.weixin.qq.com/s?src=11×tamp=1590028389&ver=2351&signature=aIT29L2e4*UKkoYukg3rGyD10AH4*zm95mg3V4FbLHh6r4F4iXk0vgpW*kDR3Lt09P7ZKr8SAcSnwEFI9uNSO8yqxXz0OT7TYRdKtOMboFIQQ8YS8czgWSPehBzSqmn7&new=1
https://mp.weixin.qq.com/s?src=11×tamp=1590035045&ver=2351&signature=WDC4lZlQdgOW9OBSE-rU-D73PQiJq1I2Lh8JijhIpBECAiSQBdPB*Xniu-ccbhjsm4pNJHf-widapHhieBatYVtGhtJEde1IiD5CR7d0J2FpCnTTW2P12WjAq-5XyTLC&new=1
https://www.cnblogs.com/echolun/p/7889848.html