在javascript中深度复制嵌套对象的数组

这个问题在这里已经有了答案:

  • 在JavaScript中深入克隆对象的最有效方法是什么? 57个答案

  • 你有两个主要选择:

  • 使用JSON.stringifyJSON.parse

    var copy = JSON.parse(JSON.stringify(original));
    

    我从来不喜欢那样。 往返文本效率低下,除非您编写替代者和reviver,否则它不会正确处理DateRegExpundefined等值。

  • 使用递归函数,如下所示:

  • var toString = Object.prototype.toString;
    function deepCopy(obj) {
        var rv;
    
        switch (typeof obj) {
            case "object":
                if (obj === null) {
                    // null => null
                    rv = null;
                } else {
                    switch (toString.call(obj)) {
                        case "[object Array]":
                            // It's an array, create a new array with
                            // deep copies of the entries
                            rv = obj.map(deepCopy);
                            break;
                        case "[object Date]":
                            // Clone the date
                            rv = new Date(obj);
                            break;
                        case "[object RegExp]":
                            // Clone the RegExp
                            rv = new RegExp(obj);
                            break;
                        // ...probably a few others
                        default:
                            // Some other kind of object, deep-copy its
                            // properties into a new object
                            rv = Object.keys(obj).reduce(function(prev, key) {
                                prev[key] = deepCopy(obj[key]);
                                return prev;
                            }, {});
                            break;
                    }
                }
                break;
            default:
                // It's a primitive, copy via assignment
                rv = obj;
                break;
        }
        return rv;
    }
    var a = [1, {foo: "bar"}, ['a', 'b'], new Date()];
    snippet.log(JSON.stringify(a));
    var b = deepCopy(a);
    snippet.log(JSON.stringify(b));
    <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
    链接地址: http://www.djcxy.com/p/6949.html

    上一篇: Deep copying array of nested objects in javascript

    下一篇: How to clone js object?