Skip to content

实现一个深克隆(考虑环) #13

Description

@ScoutYin
const deepClone = (parent) => {
   const parents = [], children = []
   const _clone = (parent) => {
     if (parent === null) return null
     if (typeof parent !== 'object' && typeof parent !== 'function') return parent
     let child
     child = Object.prototype.toString.call(parent) === '[object Array]' ? [] : {}
     const index = parents.indexOf(parent)
     if (index !== -1) {
	return children[index]
     }
     parents.push(parent)
     children.push(child)
     Object.keys(parent).forEach((key) => {
	child[key] = typeof parent[key] === 'object' ? _clone(parent[key]) : parent[key]
     })
     return child
     }
  return _clone(parent)
}

test

const obj = {
    a: 1,
    b: {
        c: [
	      {
		   d: 2
	      }
	   ]
	}
}
obj.b.c[0].d = obj.b
const newObj = deepClone(obj)
newObj.b.f = 3
console.log(obj, newObj)

Activity

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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions