码迷,mamicode.com
首页 > Web开发 > 详细

js 深拷贝

时间:2019-09-10 23:27:40      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:基础   exp   oda   asc   type   bool   rip   dash   ring   

对于深拷贝 一直使用的都是 JSON 和 lodash 的方法, 今天空下来自己手写个 深拷贝方法, 把想到的一些情况, 包括对 函数、Symbol、正则、日期对象 都做了处理。 基本上满足了了日常需求。代码如下:

// 深拷贝
function deepClone(arg) {

  let typeIncludes = ['string', 'boolean', 'number', 'undefined'] // 基础类型
  let redundanceIncludes = ['null', 'symbol', 'function', 'regexp', 'date'] // 冗余类型

  let typeObject = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()

  function dealArray(item) {
    let arr = item.map( i => {
      return deepClone(i)
    } )
    return arr
  }

  function dealObject(obj) {
    let newObj = {}
    for (const key in obj) {
      newObj[key] = deepClone(obj[key])
    }
    return newObj
  }

  if(typeIncludes.includes(typeObject(arg)) || redundanceIncludes.includes(typeObject(arg)) ) return arg

  return typeObject(arg) === 'array' ? dealArray(arg) : dealObject(arg)
  
}

有不足的地方, 还请评论区留言????

js 深拷贝

标签:基础   exp   oda   asc   type   bool   rip   dash   ring   

原文地址:https://www.cnblogs.com/vant850/p/11503528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!