Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

深度复制问题 #21

Closed
Mark24Code opened this issue Aug 9, 2019 · 1 comment
Closed

深度复制问题 #21

Mark24Code opened this issue Aug 9, 2019 · 1 comment
Assignees
Labels

Comments

@Mark24Code
Copy link
Contributor

No description provided.

@Mark24Code Mark24Code added the JS label Aug 9, 2019
@Mark24Code
Copy link
Contributor Author

首先要明白,JS里面,深度复制没有一个完美答案。

当一个数据可JSON,他的深度复制才有意义。

// 1.JSON的方法

// JSON的方法对,undefined,循环引用,正则,函数,都不行

const obj = {
  arr: [111, 222],
  obj: { key: '对象' },
  a: () => { console.log('函数') },
  date: new Date(),
  reg: /正则/ig,
  testValue: undefined,
  testValue: null,
}

const shadowCopyObj = JSON.parse(JSON.stringify(obj))

console.log(shadowCopyObj)
// output
// { arr: [ 111, 222 ],
//   obj: { key: '对象' },
//   date: '2020-04-20T08:03:01.178Z',
//   reg: {},
//   testValue: null }
//2. for ...in 递归实现

// 无法解决 函数,正则,日期,循环引用
const obj = {
  arr: [111, 222],
  obj: { key: '对象' },
  a: () => { console.log('函数') },
  date: new Date(),
  reg: /正则/ig,
  testValue: undefined,
  testValue: null,
}

function isObj(obj) {
  return (typeof obj === 'object' || typeof obj === 'function') && obj !== null
}
function deepCopy(obj) {
  let tempObj = Array.isArray(obj) ? [] : {}
  for (let key in obj) {
    tempObj[key] = isObj(obj[key]) ? deepCopy(obj[key]) : obj[key]
  }
  return tempObj
}

const deepCopyObj = deepCopy(obj)
console.log(deepCopy(obj))

// output"
// { arr: [ 111, 222 ],
//   obj: { key: '对象' },
//   a: {},
//   date: {},
//   reg: {},
//   testValue: null }



// 3. 结构性复制,可惜是异步的
//https://developer.mozilla.org/zh-CN/docs/Web/Guide/API/DOM/The_structured_clone_algorithm#%E7%9B%B8%E5%85%B3%E9%93%BE%E6%8E%A5

// 没有完整的深拷贝方案。这是一个从上层不被支持的功能。

@Mark24Code Mark24Code changed the title 手写深度复制 深度复制问题 Apr 20, 2020
@Mark24Code Mark24Code self-assigned this Apr 20, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant