1.浅拷贝

  1. // 浅拷贝
  2. let shallowCopy = function (obj) {
  3. if (typeof obj !== 'object') return
  4. let newObj = obj instanceof Array ? [] : {}
  5. for (let key in obj) {
  6. if (obj.hasOwnProperty(key)) {
  7. newObj[key] = obj[key]
  8. }
  9. }
  10. return newObj
  11. }

2.深拷贝

  1. // 递归深拷贝
  2. let deepCopy = function (obj) {
  3. if (typeof obj !== 'object') return
  4. let newObj = obj instanceof Array ? [] : {}
  5. for (var key in obj) {
  6. if (obj.hasOwnProperty(key)) {
  7. newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
  8. }
  9. }
  10. return newObj
  11. }
  1. // 入栈深拷贝
  2. let cloneDeep = function (obj) {
  3. let root = Array.isArray(obj) ? [] : {};
  4. let stack = [{
  5. parent: root,
  6. key: undefined,
  7. data: obj
  8. }]
  9. while (stack.length) {
  10. let node = stack.pop()
  11. let parent = node.parent
  12. let key = node.key
  13. let data = node.data
  14. // 初始化赋值目标,key为undefined则拷贝到父元素,否则拷贝到子元素
  15. let res = parent;
  16. if (typeof key !== 'undefined') {
  17. res = parent[key] = Array.isArray(data)? [] : {};
  18. }
  19. for (let k in data) {
  20. if(data.hasOwnProperty(k)) {
  21. if (typeof data[k] === 'object') {
  22. stack.push({parent: res, key: k, data: data[k]})
  23. } else {
  24. res[k] = data[k];
  25. }
  26. }
  27. }
  28. }
  29. return root
  30. }