moke's blog

vuePress-theme-reco moke    2017 - 2020
moke's blog

Choose mode

  • dark
  • auto
  • light
分类
  • 算法
  • 博客
  • HTTP
  • 数据结构
  • 前端
  • 文档
  • JS 基础
  • Node
标签
博客
前端
  • 知识体系
  • 前端资料
  • JavaScript 专题
  • JavaScript 基础
  • JavaScript 进阶
算法
  • 算法专题
  • 数据结构
TimeLine
GitHub (opens new window)
author-avatar

moke

56

Article

17

Tag

分类
  • 算法
  • 博客
  • HTTP
  • 数据结构
  • 前端
  • 文档
  • JS 基础
  • Node
标签
博客
前端
  • 知识体系
  • 前端资料
  • JavaScript 专题
  • JavaScript 基础
  • JavaScript 进阶
算法
  • 算法专题
  • 数据结构
TimeLine
GitHub (opens new window)
  • JavaScript 专题
  • 手动实现 call、apply、bind
  • 手动实现 JSONP
  • 手动实现 Promise
  • EventEmitter
  • 防抖与节流
  • 深浅拷贝
  • Instanceof
  • New
  • 继承相关
  • 前端路由
  • Curry
  • 工具函数

深浅拷贝

vuePress-theme-reco moke    2017 - 2020

深浅拷贝

moke 2019-04-10 23:41:17 JavaScript

# 浅拷贝

export const shallowClone = obj => {
  const result = {}

  for (const i in obj) {
    result[i] = obj[i]
  }
  return result
}

# 深拷贝

export const getType = obj =>
  Object.prototype
    .toString(obj)
    .replace(/^\[object\s(w+)\]$/, '$1')
    .toLowerCase()

export const deepClone = (parent, hash = new WeakMap()) => {
  if (parent === null) {
    return null
  }

  if (typeof parent !== 'object') {
    return parent
  }

  let child
  const type = getType(parent)
  const ConFn = parent.constructor

  switch (type) {
    case 'array':
      child = []
      break
    case 'regexp':
      child = new ConFn(parent)
      break
    case 'date':
      child = new Date(parent.getTime())
      break
    default:
      if (hash.has(parent)) {
        return hash.get(parent)
      }
      child = new ConFn(parent)
      hash.set(parent, child)
      break
  }

  for (const key in parent) {
    child[key] = deepClone(parent[key], hash)
  }

  return child
}
在 GitHub 上编辑此页 (opens new window)
最后更新时间: 4/6/2020, 8:10:15 AM