onyourroad
V2EX  ›  问与答

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

  •  
  •   onyourroad · Feb 10, 2018 · 3259 views
    This topic created in 3202 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
    bumz
    Feb 10, 2018
    1
    献上拙劣的代码实现的简陋的想法

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

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

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