Skip to content

[js] 第44天 深度克隆对象的方法有哪些,并把你认为最好的写出来 #167

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

第44天 深度克隆对象的方法有哪些,并把你认为最好的写出来

Activity

AnsonZnl

AnsonZnl commented on May 30, 2019

@AnsonZnl
Contributor

我比较喜欢使用原生的方法,足够简单,而且可以解决大多数的深拷贝。

var  obj1={
    name: '张三',
    age:14,
    friend:['小红','小白'],
    parents:{
        mother:{name: '李岚',age:34},
        father:{name: '张武',age:35}
    }
}
var obj2 = JSON.parse(JSON.stringify(obj1))
obj1.mother === obj2.parents.mother//false

wenyejie

wenyejie commented on May 30, 2019

@wenyejie

我比较喜欢使用原生的方法,足够简单,而且可以解决大多数的深拷贝。

var  obj1={
    name: '张三',
    age:14,
    friend:['小红','小白'],
    parents:{
        mother:{name: '李岚',age:34},
        father:{name: '张武',age:35}
    }
}
var obj2 = JSON.parse(JSON.stringify(obj1))
obj1.mother === obj2.parents.mother//false

是挺好的, 就是容易出bug

rocky-191

rocky-191 commented on May 30, 2019

@rocky-191

递归调用拷贝。json.parse可以解决一般的对象深拷贝,但是函数类型的对象就不行了

tzjoke

tzjoke commented on May 31, 2019

@tzjoke

全面的deep clone最坑爹的一点就是对象内部引用自己

myprelude

myprelude commented on Jun 13, 2019

@myprelude
  • 容易理解是 JSON.parse JSON.stringify
  • 递归
// 深度遍历

// 广度遍历
DarthVaderrr

DarthVaderrr commented on Jul 4, 2019

@DarthVaderrr

数组: newArr=[...oldArr]
只包含数据的对象: JSON.parse
复杂对象:递归,解构

zlx362211854

zlx362211854 commented on Jul 15, 2019

@zlx362211854

数组: newArr=[...oldArr]
只包含数据的对象: JSON.parse
复杂对象:递归,解构

对一维数组,才能使用newArr=[...oldArr]

getanimation

getanimation commented on Jul 17, 2019

@getanimation

数组clone:Array.from( )
对象clone:JSON.parse(JSON.stringify( ))

chenyouf1996

chenyouf1996 commented on Jul 22, 2019

@chenyouf1996
function deepClone(obj) {
  if (Object.prototype.toString.call(obj).slice(8, -1) === 'Object') {
    var newObj = {}
    for (const key in obj) {
      newObj[key]=deepClone(obj[key])
    }
    return newObj
  } else if (Object.prototype.toString.call(obj).slice(8, -1) === 'Array') {
    var newArr = []
    for (const index in obj) {
      newArr[index]=deepClone(obj[index])
    }
    return newArr
  }
  return obj
}
shufangyi

shufangyi commented on Jul 23, 2019

@shufangyi
const isType = type => target =>
  Object.prototype.toString.call(target) === `[object ${type}]`

const isArray = isType('Array')
const isObject = isType('Object')

function extend(target, source, deep) {
  for (const key in source)
    if (source.hasOwnProperty(key))
      if (deep && (isArray(source[key]) || isObject(source[key]))) {
        if (isArray(source[key]) && !isArray(target[key])) target[key] = []
        if (isObject(source[key]) && !isObject(target[key])) target[key] = {}
        extend(target[key], source[key], deep)
      } else if (source[key] !== undefined) target[key] = source[key]
}

function clone(target) {
  let deep,
    args = [].slice.call(arguments, 1)
  if (typeof target === 'boolean') {
    deep = target
    target = args.shift()
  }
  args.forEach(source => extend(target, source, deep))
  return target
}
hc951221

hc951221 commented on Aug 8, 2019

@hc951221

我习惯用json.parser(json.stringify()),
麻烦点的是自己写个方法把对象遍历出来赋值

jiamianmao

jiamianmao commented on Aug 10, 2019

@jiamianmao

数组: newArr=[...oldArr]
只包含数据的对象: JSON.parse
复杂对象:递归,解构

这个小老弟, 扩展运算符那个是浅拷贝,深拷贝最简单的是 JSON.parse JSON.stringify

但对于 undefined function symbol 是会忽略的。

你API层面得到的都是浅拷贝。

通常来说,都是递归来实现一个 deepClone

ducky-YFH

ducky-YFH commented on Oct 22, 2019

@ducky-YFH
function deepCopy(newObj, oldObj) {
  for (var key in oldObj) {
    var item = oldObj[key]
    if (item instanceof Array) {
      newObj[key] = [];
      deepCopy(newObj[key], item);
    }
    else if (item instanceof Object) {
      newObj[key] = {};
      deepCopy(newObj[key], item);
    }
    else {
      newObj[key] = item;
    }
  }
  return newObj;
}

15 remaining items

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @smile-2008@wenyejie@haizhilin2013@laboonly@rocky-191

        Issue actions

          [js] 第44天 深度克隆对象的方法有哪些,并把你认为最好的写出来 · Issue #167 · haizlin/fe-interview