ECMAScript5 deep copy of object and arrays

I'd hope to find an example code to do a deep copying of objects in ECMAScript5.

The copying should be able to clone

  • Nested objects

  • Nested arrays

  • Nested objects in arrays (clone each array item individually)

  • Note: jQuery.extend() does not seem to handle case 3). Also, I'd hope to do this in clean ECMAScript. Quick googling did not bring up any worthy implementations.


    I finally settled to jQuery.extend() as I couldn't find other good implementations

    http://api.jquery.com/jQuery.extend/


    if you want a one-liner (removes object refs by iterating through referenced objects to retrieve primitives, concats one large string, then parses the string into a new object with it's own primitive leaf nodes)

    JSON.parse(JSON.stringify(obj))
    

    or if you need to perform many copies

    function deepCopy(o) {
        var copy = o,k;
    
        if (o && typeof o === 'object') {
            copy = Object.prototype.toString.call(o) === '[object Array]' ? [] : {};
            for (k in o) {
                copy[k] = deepCopy(o[k]);
            }
        }
    
        return copy;
    }
    

    performance comparison


    使用toSource方法的仿真来复制对象:

        <script type="text/javascript">
        Object.prototype.getSource = function() {
          var output = [], temp;
          for (var i in this) {
              if (this.hasOwnProperty(i)) {
                  temp = i + ":";
                  switch (typeof this[i]) {
                      case "object" :
                          temp += this[i].getSource();
                          break;
                      case "string" :
                          temp += """ + this[i] + """;    // add in some code to escape quotes
                          break;
                      default :
                          temp += this[i];
                  }
                  output.push(temp);
              }
          }
          return "{" + output.join() + "}";
          }
          var baz = {"alpha":{"beta":{"charlie": ["delta","epsilon",{"omega":"zeta"}]}}};
          !!Object.prototype.toSource ? alert((baz).toSource() ) : alert((baz).getSource() );
        </script>
    
    链接地址: http://www.djcxy.com/p/40678.html

    上一篇: Angular中angular.copy的替代方法是什么?

    下一篇: 对象和数组的ECMAScript5深层副本