How to implement deep copy and shallow copy

Shallow copy: Just create data and simply copy the reference address in the stack. When the value of the new copy is modified, the copied object will also be modified.

实现方式:
Object.assign;
Array.prototype.slice() ;
Array.prototype.concat();
使用拓展运算符实现的复制([…]);

Deep copy: It opens a new stack. The properties of the two objects are exactly the same, but correspond to two different addresses. If one object is modified, the properties of the other object will not change.

实现方式:
_.cloneDeep();
jQuery.extend(),(jQuery 中的 $.extend (添加true就是深拷贝,不添加就是浅拷贝));
MessageChannel();
JSON.stringfy(),(JSON.parse(JSON.stringify(待拷贝对象)),此拷贝的缺点:没法拷贝内部函数);
手写递归循环;

To copy an array:

1.扩展运算符(浅拷贝) 不能有效拷贝多维数据
2.for()循环(浅拷贝) 不能有效拷贝多维数组
3.while()循环(浅拷贝)
4.Array.map(浅拷贝) callback函数处理当前的数组,并返回一个新的数组元素
5.Array.filter(浅拷贝) 返回数组和过滤条件有关
6.Array.reduce(浅拷贝) 对每个元素执行提供的reducer函数,将其结果汇总为单个返回值
7.Array.slice(浅拷贝) 指定start,end的index从原数组返回一个浅拷贝的数组
8.JSON.parse & JSON.stringfy(深拷贝) 前者将对象转为字符串,后者将得到的字符串转回对象,可以安全的拷贝深度嵌套的对象/数组
9.Array.concat(浅拷贝)
10.Array.from(浅拷贝) 将任何可迭代对象转换为数组,给一个数组返回一个浅拷贝 

Guess you like

Origin blog.csdn.net/lzfengquan/article/details/132540042