V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
onyourroad
V2EX  ›  问与答

JavaScript 深拷贝(只考虑对象和数组类型),请问大家递归深拷贝的方法可以使用栈或者队列来实现呢?怎么实现呢?自己写不明白了。。

  •  
  •   onyourroad · 2018-02-10 09:50:31 +08:00 · 2193 次点击
    这是一个创建于 2260 天前的主题,其中的信息可能已经有所发展或是发生改变。

    以下是我写的简单的递归方式的深拷贝。

      function copy(source) {
        var key, target
        if (type(source) === "array") {
          target = []
          for (key = 0; key < source.length; key++) {
            if (type(source[key]) === "array" || "object") {
              target[key] = copy(source[key])
            } else if (source[key] !== undefined) target[key] = source[key]
          }
        } else if (type(source) === "object") {
          target = {}
          for (key in source) {
            if (type(source[key]) === "array" || "object") {
              target[key] = copy(source[key])
            } else if (source[key] !== undefined) target[key] = source[key]
          }
        }
    
        return target
      }
    
    10 条回复    2018-02-11 10:02:11 +08:00
    bumz
        1
    bumz  
       2018-02-10 10:27:56 +08:00
    献上拙劣的代码实现的简陋的想法

    https://gist.github.com/bumfo/b41088a717a0ee633fb91ce1b334b4fb
    ulala
        2
    ulala  
       2018-02-10 10:49:05 +08:00 via iPad
    if (type(source[key]) === "array" || "object") {
    这是要表达什么?
    onyourroad
        3
    onyourroad  
    OP
       2018-02-10 11:00:46 +08:00
    @bumz 看不到。。
    iFun
        4
    iFun  
       2018-02-10 11:23:53 +08:00
    去看下 lodash 怎么写的 deepcopy
    sneezry
        5
    sneezry  
       2018-02-10 13:50:24 +08:00 via iPhone
    如果只考虑数组和对象的话,有个很 tricky 的办法

    newObj = JSON.parse(JSON.stringify(obj))

    递归的话最底层是基本类型,string 啊 number 啊 boolean 啊 null 啊什么的,如果是这些类型 copy 要返回数据本身。
    Cbdy
        6
    Cbdy  
       2018-02-10 18:21:14 +08:00 via Android
    单层次的
    对象
    const t = { ...s }
    数组
    const t = [ ...s ]
    bumz
        7
    bumz  
       2018-02-10 19:18:36 +08:00
    bumz
        8
    bumz  
       2018-02-10 19:20:41 +08:00   ❤️ 1
    简单地说,深拷贝等价于遍历树,不用递归就是 non-recursive tree traversal
    bumz
        9
    bumz  
       2018-02-10 19:21:32 +08:00
    不过这个假设对象有循环引用就不行了,需要加一个判回
    onyourroad
        10
    onyourroad  
    OP
       2018-02-11 10:02:11 +08:00
    @bumz 谢谢了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2761 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 12:12 · PVG 20:12 · LAX 05:12 · JFK 08:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.