V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
onyourroad
V2EX  ›  问与答

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

  •  
  •   onyourroad · Feb 10, 2018 · 2780 views
    This topic created in 3002 days ago, the information mentioned may be changed or developed.

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

      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 replies    2018-02-11 10:02:11 +08:00
    bumz
        1
    bumz  
       Feb 10, 2018
    献上拙劣的代码实现的简陋的想法

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

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

    递归的话最底层是基本类型,string 啊 number 啊 boolean 啊 null 啊什么的,如果是这些类型 copy 要返回数据本身。
    Cbdy
        6
    Cbdy  
       Feb 10, 2018 via Android
    单层次的
    对象
    const t = { ...s }
    数组
    const t = [ ...s ]
    bumz
        7
    bumz  
       Feb 10, 2018
    bumz
        8
    bumz  
       Feb 10, 2018   ❤️ 1
    简单地说,深拷贝等价于遍历树,不用递归就是 non-recursive tree traversal
    bumz
        9
    bumz  
       Feb 10, 2018
    不过这个假设对象有循环引用就不行了,需要加一个判回
    onyourroad
        10
    onyourroad  
    OP
       Feb 11, 2018
    @bumz 谢谢了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2456 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 05:15 · PVG 13:15 · LAX 22:15 · JFK 01:15
    ♥ Do have faith in what you're doing.