在JavaScript中深度克隆对象的最有效方法是什么?

本文探讨了在JavaScript中深度克隆对象的各种方法,包括结构化克隆、JSON.parse/JSON.stringify、使用库以及ES6特性。文章指出,虽然JSON方法简单但可能会丢失数据,而结构化克隆在Node.js中有实验性支持,浏览器中则需要通过MessageChannel实现。文中还推荐了一些可靠的库,如lodash的_.cloneDeep,并提供了自定义实现的示例。
摘要由CSDN通过智能技术生成

克隆JavaScript对象的最有效方法是什么? 我见过obj = eval(uneval(o)); 正在使用,但这是非标准的,仅受Firefox支持

我已经完成了obj = JSON.parse(JSON.stringify(o)); 但质疑效率。

我还看到了具有各种缺陷的递归复制功能。
我很惊讶没有规范的解决方案存在。


#1楼

码:

// extends 'from' object with members from 'to'. If 'to' is null, a deep clone of 'from' is returned
function extend(from, to)
{
    if (from == null || typeof from != "object") return from;
    if (from.constructor != Object && from.constructor != Array) return from;
    if (from.constructor == Date || from.constructor == RegExp || from.constructor == Function ||
        from.constructor == String || from.constructor == Number || from.constructor == Boolean)
        return new from.constructor(from);

    to = to || new from.constructor();

    for (var name in from)
    {
        to[name] = typeof to[name] == "undefined" ? extend(from[name], null) : to[name];
    }

    return to;
}

测试:

var obj =
{
    date: new Date(),
    func: function(q) { return 1 + q; },
    num: 123,
    text: "asdasd",
    array: [1, "asd"],
    regex: new RegExp(/aaa/i),
    subobj:
    {
        num: 234,
        text: "asdsaD"
    }
}

var clone = extend(obj);

#2楼

结构化克隆

HTML标准包括一个内部结构化克隆/序列化算法 ,该算法可以创建对象的深层克隆。 它仍然仅限于某些内置类型,但除JSON支持的几种类型外,它还支持日期,正则表达式,地图,集合,Blob,文件列表,ImageData,稀疏数组,类型数组,并且将来可能还会更多。 它还在克隆的数据中保留引用,从而使其能够支持会导致JSON错误的循环和递归结构。

Node.js中的支持:实验性

当前(从节点11开始)Node.js中的v8模块直接公开了结构化序列化API ,但是此功能仍标记为“实验性”,并且在将来的版本中可能会更改或删除。 如果使用兼容版本,则克隆对象非常简单:

const v8 = require('v8');

const structuredClone = obj => {
  return v8.deserialize(v8.serialize(obj));
};

浏览器中的直接支持:也许最终? 😐

浏览器当前不提供结构化克隆算法的直接接口,但是在GitHub上的whatwg / html#793中已经讨论了全局的structuredClone()函数。 按照目前的建议,将其用于大多数目的将非常简单:

const clone = structuredClone(original);

除非提供此功能,否则浏览器的结构化克隆实现只能间接公开。

异步解决方法:可用。 😕

使用现有API创建结构化克隆的一种较低开销的方法是通过MessageChannels的一个端口发布数据。 另一个端口将发出message事件,并带有附件.data的结构化克隆。 不幸的是,侦听这些事件必然是异步的,而同步替代方法则不太实用。

class StructuredCloner {
  constructor() {
    this.pendingClones_ = new Map();
    this.nextKey_ = 0;

    const channel = new MessageChannel();
    this.inPort_ = channel.port1;
    this.outPort_ = channel.port2;

    this.outPort_.onmessage = ({data: {key, value}}) => {
      const resolve = this.pendingClones_.get(key);
      resolve(value);
      this.pendingClones_.delete(key);
    };
    this.outPort_.start();
  }

  cloneAsync(value) {
    return new Promise(resolve => {
      const key = this.nextKey_++;
      this.pendingClones_.set(key, resolve);
      this.inPort_.postMessage({key, value});
    });
  }
}

const structuredCloneAsync = window.structuredCloneAsync =
    StructuredCloner.prototype.cloneAsync.bind(new StructuredCloner);

使用示例:

const main = async () => {
  const original = { date: new Date(), number: Math.random() };
  original.self = original;

  const clone = await structuredCloneAsync(original);

  // They're different objects:
  console.assert(original !== clone);
  console.assert(original.date !== clone.date);

  // They're cyclical:
  console.assert(original.self === original);
  console.assert(clone.self === clone);

  // They contain equivalent values:
  console.assert(original.number === clone.number);
  console.assert(Number(original.date) === Number(clone.date));

  console.log("Assertions complete.");
};

main();

同步解决方法:糟糕! 🤢

没有同步创建结构化克隆的良好选择。 这里有一些不切实际的技巧。

history.pushState()history.replaceState()都创建其第一个参数的结构化克隆,并将该值分配给history.state 。 您可以使用它来创建任何对象的结构化克隆,如下所示:

const structuredClone = obj => {
  const oldState = history.state;
  history.replaceState(obj, null);
  const clonedObj = history.state;
  history.replaceState(oldState, null);
  return clonedObj;
};

使用示例:

 'use strict'; const main = () => { const original = { date: new Date(), number: Math.random() }; original.self = original; const clone = structuredClone(original); // They're different objects: console.assert(original !== clone); console.assert(original.date !== clone.date); // They're cyclical: console.assert(original.self === original); console.assert(clone.self === clone); // They contain equivalent values: console.assert(original.number === clone.number); console.assert(Number(original.date) === Number(clone.date)); console.log("Assertions complete."); }; const structuredClone = obj => { const oldState = history.state; history.replaceState(obj, null); const clonedObj = history.state; history.replaceState(oldState, null); return clonedObj; }; main(); 

尽管是同步的,但是这可能会非常慢。 这会产生与操纵浏览器历史记录相关的所有开销。 反复调用此方法可能会导致Chrome暂时无响应。

Notification构造函数创建其关联数据的结构化克隆。 它还尝试向用户显示浏览器通知,但是除非您请求了通知权限,否则此操作将以静默方式失败。 如果您有其他用途的许可,我们将立即关闭我们创建的通知。

const structuredClone = obj => {
  const n = new Notification('', {data: obj, silent: true});
  n.onshow = n.close.bind(n);
  return n.data;
};

使用示例:

 'use strict'; const main = () => { const original = { date: new Date(), number: Math.random() }; original.self = original; const clone = structuredClone(original); // They're different objects: console.assert(original !== clone); console.assert(original.date !== clone.date); // They're cyclical: console.assert(original.self === original); console.assert(clone.self === clone); // They contain equivalent values: console.assert(original.number === clone.number); console.assert(Number(original.date) === Number(clone.date)); console.log("Assertions complete."); }; const structuredClone = obj => { const n = new Notification('', {data: obj, silent: true}); n.close(); return n.data; }; main(); 


#3楼

浅拷贝单线版ECMAScript第5版 ):

var origin = { foo : {} };
var copy = Object.keys(origin).reduce(function(c,k){c[k]=origin[k];return c;},{});

console.log(origin, copy);
console.log(origin == copy); // false
console.log(origin.foo == copy.foo); // true

浅拷贝单线( ECMAScript第6版 ,2015年):

var origin = { foo : {} };
var copy = Object.assign({}, origin);

console.log(origin, copy);
console.log(origin == copy); // false
console.log(origin.foo == copy.foo); // true

#4楼

这是一个全面的clone()方法,可以克隆任何JavaScript对象。 它处理几乎所有情况:

function clone(src, deep) {

    var toString = Object.prototype.toString;
    if (!src && typeof src != "object") {
        // Any non-object (Boolean, String, Number), null, undefined, NaN
        return src;
    }

    // Honor native/custom clone methods
    if (src.clone && toString.call(src.clone) == "[object Function]") {
        return src.clone(deep);
    }

    // DOM elements
    if (src.nodeType && toString.call(src.cloneNode) == "[object Function]") {
        return src.cloneNode(deep);
    }

    // Date
    if (toString.call(src) == "[object Date]") {
        return new Date(src.getTime());
    }

    // RegExp
    if (toString.call(src) == "[object RegExp]") {
        return new RegExp(src);
    }

    // Function
    if (toString.call(src) == "[object Function]") {

        //Wrap in another method to make sure == is not true;
        //Note: Huge performance issue due to closures, comment this :)
        return (function(){
            src.apply(this, arguments);
        });
    }

    var ret, index;
    //Array
    if (toString.call(src) == "[object Array]") {
        //[].slice(0) would soft clone
        ret = src.slice();
        if (deep) {
            index = ret.length;
            while (index--) {
                ret[index] = clone(ret[index], true);
            }
        }
    }
    //Object
    else {
        ret = src.constructor ? new src.constructor() : {};
        for (var prop in src) {
            ret[prop] = deep
                ? clone(src[prop], true)
                : src[prop];
        }
    }
    return ret;
};

#5楼

如果没有内置的,可以尝试:

function clone(obj) {
    if (obj === null || typeof (obj) !== 'object' || 'isActiveClone' in obj)
        return obj;

    if (obj instanceof Date)
        var temp = new obj.constructor(); //or new Date(obj);
    else
        var temp = obj.constructor();

    for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            obj['isActiveClone'] = null;
            temp[key] = clone(obj[key]);
            delete obj['isActiveClone'];
        }
    }
    return temp;
}

#6楼

function clone(obj)
 { var clone = {};
   clone.prototype = obj.prototype;
   for (property in obj) clone[property] = obj[property];
   return clone;
 }

#7楼

原生深克隆

它被称为“结构化克隆”,可在Node 11及更高版本上进行实验性工作,并有望登陆浏览器。 有关更多详细信息,请参见此答案

快速克隆而数据丢失-JSON.parse / stringify

如果您不使用Date ,函数, undefinedInfinity ,RegExps,Maps,Sets,Blobs,FileLists,ImageDatas,Sparse Arrays,Typed Arrays或对象中的其他复杂类型,则可以使用一种非常简单的方法来深度克隆对象:

JSON.parse(JSON.stringify(object))

 const a = { string: 'string', number: 123, bool: false, nul: null, date: new Date(), // stringified undef: undefined, // lost inf: Infinity, // forced to 'null' re: /.*/, // lost } console.log(a); console.log(typeof a.date); // Date object const clone = JSON.parse(JSON.stringify(a)); console.log(clone); console.log(typeof clone.date); // result of .toISOString() 

有关基准,请参阅Corban的答案

使用库进行可靠的克隆

由于克隆对象并非易事(复杂类型,循环引用,函数等),因此大多数主要库都提供了克隆对象的功能。 不要重新发明轮子 -如果您已经在使用库,请检查它是否具有对象克隆功能。 例如,

ES6

为了完整起见,请注意ES6提供了两种浅表复制机制: Object.assign()spread操作符


#8楼

有一个库(称为“克隆”) ,可以很好地完成此任务。 它提供了我所知道的任意对象的最完整的递归克隆/复制。 它还支持循环引用,但其他答案尚未涵盖。

您也可以在npm上找到它 。 它可以用于浏览器以及Node.js。

这是有关如何使用它的示例:

用安装

npm install clone

或将其与Ender打包在一起。

ender build clone [...]

您也可以手动下载源代码。

然后,您可以在源代码中使用它。

var clone = require('clone');

var a = { foo: { bar: 'baz' } };  // inital value of a
var b = clone(a);                 // clone a -> b
a.foo.bar = 'foo';                // change a

console.log(a);                   // { foo: { bar: 'foo' } }
console.log(b);                   // { foo: { bar: 'baz' } }

(免责声明:我是图书馆的作者。)


#9楼

这是上面ConroyP答案的一个版本,即使构造函数具有必需的参数,该版本仍然有效:

//If Object.create isn't already defined, we just do the simple shim,
//without the second argument, since that's all we need here
var object_create = Object.create;
if (typeof object_create !== 'function') {
    object_create = function(o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

function deepCopy(obj) {
    if(obj == null || typeof(obj) !== 'object'){
        return obj;
    }
    //make sure the returned object has the same prototype as the original
    var ret = object_create(obj.constructor.prototype);
    for(var key in obj){
        ret[key] = deepCopy(obj[key]);
    }
    return ret;
}

我的simpleoo库中也提供了此功能。

编辑:

这是一个更健壮的版本(由于Justin McCandless现在也支持循环引用):

/**
 * Deep copy an object (make copies of all its object properties, sub-properties, etc.)
 * An improved version of http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone
 * that doesn't break if the constructor has required parameters
 * 
 * It also borrows some code from http://stackoverflow.com/a/11621004/560114
 */ 
function deepCopy(src, /* INTERNAL */ _visited, _copiesVisited) {
    if(src === null || typeof(src) !== 'object'){
        return src;
    }

    //Honor native/custom clone methods
    if(typeof src.clone == 'function'){
        return src.clone(true);
    }

    //Special cases:
    //Date
    if(src instanceof Date){
        return new Date(src.getTime());
    }
    //RegExp
    if(src instanceof RegExp){
        return new RegExp(src);
    }
    //DOM Element
    if(src.nodeType && typeof src.cloneNode == 'function'){
        return src.cloneNode(true);
    }

    // Initialize the visited objects arrays if needed.
    // This is used to detect cyclic references.
    if (_visited === undefined){
        _visited = [];
        _copiesVisited = [];
    }

    // Check if this object has already been visited
    var i, len = _visited.length;
    for (i = 0; i < len; i++) {
        // If so, get the copy we already made
        if (src === _visited[i]) {
            return _copiesVisited[i];
        }
    }

    //Array
    if (Object.prototype.toString.call(src) == '[object Array]') {
        //[].slice() by itself would soft clone
        var ret = src.slice();

        //add it to the visited array
        _visited.push(src);
        _copiesVisited.push(ret);

        var i = ret.length;
        while (i--) {
            ret[i] = deepCopy(ret[i], _visited, _copiesVisited);
        }
        return ret;
    }

    //If we've reached here, we have a regular object

    //make sure the returned object has the same prototype as the original
    var proto = (Object.getPrototypeOf ? Object.getPrototypeOf(src): src.__proto__);
    if (!proto) {
        proto = src.constructor.prototype; //this line would probably only be reached by very old browsers 
    }
    var dest = object_create(proto);

    //add this object to the visited array
    _visited.push(src);
    _copiesVisited.push(dest);

    for (var key in src) {
        //Note: this does NOT preserve ES5 property attributes like 'writable', 'enumerable', etc.
        //For an example of how this could be modified to do so, see the singleMixin() function
        dest[key] = deepCopy(src[key], _visited, _copiesVisited);
    }
    return dest;
}

//If Object.create isn't already defined, we just do the simple shim,
//without the second argument, since that's all we need here
var object_create = Object.create;
if (typeof object_create !== 'function') {
    object_create = function(o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

#10楼

根据您的目标是克隆“普通的旧JavaScript对象”,我有两个很好的答案。

我们还假设您的意图是创建一个完整的克隆,而没有原型引用返回到源对象。 如果您对完整克隆不感兴趣,则可以使用其他一些答案(Crockford模式)中提供的许多Object.clone()例程。

对于普通的旧JavaScript对象,在现代运行时中克隆对象的一种经过实践检验的好方法非常简单:

var clone = JSON.parse(JSON.stringify(obj));

请注意,源对象必须是纯JSON对象。 也就是说,其所有嵌套属性都必须是标量(如布尔值,字符串,数组,对象等)。 任何功能或特殊对象(如RegExp或Date)都不会被克隆。

有效率吗? 哎呀。 我们尝试了各种克隆方法,并且效果最好。 我敢肯定,有些忍者会想出一种更快的方法。 但是我怀疑我们在谈论边际收益。

这种方法既简单又易于实现。 将其包装为便利功能,如果您确实需要榨取一些收益,请稍后再试。

现在,对于非普通的JavaScript对象,没有一个真正简单的答案。 实际上,不可能是因为JavaScript函数和内部对象状态的动态性质。 深入克隆内部函数的JSON结构需要您重新创建这些函数及其内部上下文。 而且JavaScript根本没有标准化的方法。

再一次,正确的方法是通过在代码中声明并重用的便捷方法。 便捷方法可以使您对自己的对象有所了解,从而可以确保在新对象中正确地重新创建图形。

我们是自己编写的,但是这里介绍了我所见过的最好的通用方法:

http://davidwalsh.name/javascript-clone

这是正确的想法。 作者(David Walsh)评论了广义函数的克隆。 您可以根据自己的用例选择执行此操作。

主要思想是您需要按类型专门处理函数的实例化(或可以说是原型类)。 在这里,他提供了RegExp和Date的一些示例。

该代码不仅简短,而且可读性强。 扩展很容易。

这样有效吗? 哎呀。 鉴于目标是产生一个真正的深拷贝克隆,那么您将不得不遍历源对象图的成员。 使用这种方法,您可以精确调整要处理的子成员以及如何手动处理自定义类型。

所以你去了。 两种方法。 我认为两者都是有效的。


#11楼

Lodash有一个不错的_.cloneDeep(value)方法:

var objects = [{ 'a': 1 }, { 'b': 2 }];

var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false

#12楼

这就是我正在使用的:

function cloneObject(obj) {
    var clone = {};
    for(var i in obj) {
        if(typeof(obj[i])=="object" && obj[i] != null)
            clone[i] = cloneObject(obj[i]);
        else
            clone[i] = obj[i];
    }
    return clone;
}

#13楼

var clone = function() {
    var newObj = (this instanceof Array) ? [] : {};
    for (var i in this) {
        if (this[i] && typeof this[i] == "object") {
            newObj[i] = this[i].clone();
        }
        else
        {
            newObj[i] = this[i];
        }
    }
    return newObj;
}; 

Object.defineProperty( Object.prototype, "clone", {value: clone, enumerable: false});

#14楼

按性能进行深度复制:从最佳到最差

  • 重新分配“ =”(仅字符串数组,数字数组)
  • 切片(字符串数组,数字数组-仅)
  • 串联(仅字符串数组,数字数组)
  • 自定义功能:for循环或递归复制
  • jQuery的$ .extend
  • JSON.parse(仅字符串数组,数字数组,对象数组)
  • Underscore.js的_.clone(字符串数组,若干阵列-只)
  • Lo-Dash的_.cloneDeep

深度复制一个字符串或数字数组(一个级别-没有引用指针):

当数组包含数字和字符串时-诸如.slice()、. concat()、. splice()之类的函数,赋值运算符“ =”和Underscore.js的clone函数; 将复制该数组的元素。

重新分配表现最快的地方:

var arr1 = ['a', 'b', 'c'];
var arr2 = arr1;
arr1 = ['a', 'b', 'c'];

而且.slice()的性能优于.concat(), http: //jsperf.com/duplicate-array-slice-vs-concat/3

var arr1 = ['a', 'b', 'c'];  // Becomes arr1 = ['a', 'b', 'c']
var arr2a = arr1.slice(0);   // Becomes arr2a = ['a', 'b', 'c'] - deep copy
var arr2b = arr1.concat();   // Becomes arr2b = ['a', 'b', 'c'] - deep copy

深度复制对象数组(两个或多个级别-参考指针):

var arr1 = [{object:'a'}, {object:'b'}];

编写一个自定义函数(具有比$ .extend()或JSON.parse更快的性能):

function copy(o) {
   var out, v, key;
   out = Array.isArray(o) ? [] : {};
   for (key in o) {
       v = o[key];
       out[key] = (typeof v === "object" && v !== null) ? copy(v) : v;
   }
   return out;
}

copy(arr1);

使用第三方实用程序功能:

$.extend(true, [], arr1); // Jquery Extend
JSON.parse(arr1);
_.cloneDeep(arr1); // Lo-dash

jQuery的$ .extend具有更好的性能:


#15楼

// obj target object, vals source object
var setVals = function (obj, vals) {
    if (obj && vals) {
        for (var x in vals) {
            if (vals.hasOwnProperty(x)) {
                if (obj[x] && typeof vals[x] === 'object') {
                    obj[x] = setVals(obj[x], vals[x]);
                } else {
                    obj[x] = vals[x];
                }
            }
        }
    }
    return obj;
};

#16楼

以下创建同一对象的两个实例。 我找到了它,目前正在使用它。 它简单易用。

var objToCreate = JSON.parse(JSON.stringify(cloneThis));

#17楼

对于想要使用JSON.parse(JSON.stringify(obj))版本但又不会丢失Date对象的人们,可以使用parse方法第二个参数将字符串转换回Date:

function clone(obj) {
  var regExp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
  return JSON.parse(JSON.stringify(x), function(k, v) {
    if (typeof v === 'string' && regExp.test(v))
      return new Date(v);
    return v;
  });
}

#18楼

在一行代码中克隆(而非深度克隆)对象的有效方法

Object.assign方法是ECMAScript 2015(ES6)标准的一部分,可以完全满足您的需求。

var clone = Object.assign({}, obj);

Object.assign()方法用于将所有可枚举的自身属性的值从一个或多个源对象复制到目标对象。

阅读更多...

支持旧版浏览器的polyfill

if (!Object.assign) {
  Object.defineProperty(Object, 'assign', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function(target) {
      'use strict';
      if (target === undefined || target === null) {
        throw new TypeError('Cannot convert first argument to object');
      }

      var to = Object(target);
      for (var i = 1; i < arguments.length; i++) {
        var nextSource = arguments[i];
        if (nextSource === undefined || nextSource === null) {
          continue;
        }
        nextSource = Object(nextSource);

        var keysArray = Object.keys(nextSource);
        for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
          var nextKey = keysArray[nextIndex];
          var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
          if (desc !== undefined && desc.enumerable) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
      return to;
    }
  });
}

#19楼

只是因为我没有看到AngularJS并以为人们可能想知道...

angular.copy还提供了深度复制对象和数组的方法。


#20楼

Crockford建议(我更喜欢)使用此功能:

function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

var newObject = object(oldObject);

它很简洁,可以按预期工作,您不需要库。


编辑:

这是Object.create ,因此您也可以使用它。

var newObject = Object.create(oldObject);

注意:如果使用其中的一些,则使用hasOwnProperty某些迭代可能会遇到问题。 因为, create一个继承了oldObject新的空对象。 但是对于克隆对象仍然有用且实用。

例如oldObject.a = 5;

newObject.a; // is 5

但:

oldObject.hasOwnProperty(a); // is true
newObject.hasOwnProperty(a); // is false

#21楼

AngularJS

好吧,如果您使用的是角度,也可以这样做

var newObject = angular.copy(oldObject);

#22楼

对于类似数组的对象,似乎还没有理想的深度克隆运算符。 如下代码所示,John Resig的jQuery克隆器将具有非数字属性的数组转换为非数组对象,而RegDwight的JSON克隆器删除了非数字属性。 以下测试在多种浏览器上说明了这些要点:

function jQueryClone(obj) {
   return jQuery.extend(true, {}, obj)
}

function JSONClone(obj) {
   return JSON.parse(JSON.stringify(obj))
}

var arrayLikeObj = [[1, "a", "b"], [2, "b", "a"]];
arrayLikeObj.names = ["m", "n", "o"];
var JSONCopy = JSONClone(arrayLikeObj);
var jQueryCopy = jQueryClone(arrayLikeObj);

alert("Is arrayLikeObj an array instance?" + (arrayLikeObj instanceof Array) +
      "\nIs the jQueryClone an array instance? " + (jQueryCopy instanceof Array) +
      "\nWhat are the arrayLikeObj names? " + arrayLikeObj.names +
      "\nAnd what are the JSONClone names? " + JSONCopy.names)

#23楼

Cloning对象一直是JS的关注点,但在ES6之前就已经存在了,我在下面列出了在JavaScript中复制对象的不同方法,假设您在下面有对象,并希望对其进行深入的复制:

var obj = {a:1, b:2, c:3, d:4};

在不更改原点的情况下,有几种方法可以复制该对象:

1)ES5 +,使用简单的功能为您制作副本:

function deepCopyObj(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    if (obj instanceof Date) {
        var copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }
    if (obj instanceof Array) {
        var copy = [];
        for (var i = 0, len = obj.length; i < len; i++) {
            copy[i] = cloneSO(obj[i]);
        }
        return copy;
    }
    if (obj instanceof Object) {
        var copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = cloneSO(obj[attr]);
        }
        return copy;
    }
    throw new Error("Unable to copy obj this object.");
}

2)ES5 +,使用JSON.parse和JSON.stringify。

var  deepCopyObj = JSON.parse(JSON.stringify(obj));

3)AngularJs:

var  deepCopyObj = angular.copy(obj);

4)jQuery:

var deepCopyObj = jQuery.extend(true, {}, obj);

5)UnderscoreJs和Loadash:

var deepCopyObj = _.cloneDeep(obj); //latest version UndescoreJs makes shallow copy

希望这些帮助...


#24楼

我不同意这里的投票。 递归深层 克隆比提到的JSON.parse(JSON.stringify(obj))方法要快得多

  • Jsperf在这里排名第一: https : //jsperf.com/deep-copy-vs-json-stringify-json-parse/5
  • 上面答案中的Jsben进行了更新,以显示递归深层克隆击败了所有其他提到的问题: http : //jsben.ch/13YKQ

以下是供快速参考的功能:

function cloneDeep (o) {
  let newO
  let i

  if (typeof o !== 'object') return o

  if (!o) return o

  if (Object.prototype.toString.apply(o) === '[object Array]') {
    newO = []
    for (i = 0; i < o.length; i += 1) {
      newO[i] = cloneDeep(o[i])
    }
    return newO
  }

  newO = {}
  for (i in o) {
    if (o.hasOwnProperty(i)) {
      newO[i] = cloneDeep(o[i])
    }
  }
  return newO
}

#25楼

假设您的对象中只有变量,而没有任何函数,则可以使用:

var newObject = JSON.parse(JSON.stringify(oldObject));

#26楼

用JavaScript深度复制对象(我认为最好和最简单)

1.使用JSON.parse(JSON.stringify(object));

var obj = { 
  a: 1,
  b: { 
    c: 2
  }
}
var newObj = JSON.parse(JSON.stringify(obj));
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } } 

2.使用创建的方法

function cloneObject(obj) {
    var clone = {};
    for(var i in obj) {
        if(obj[i] != null &&  typeof(obj[i])=="object")
            clone[i] = cloneObject(obj[i]);
        else
            clone[i] = obj[i];
    }
    return clone;
}

var obj = { 
  a: 1,
  b: { 
    c: 2
  }
}
var newObj = cloneObject(obj);
obj.b.c = 20;

console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } } 

3.使用Lo-Dash的_.cloneDeep链接lodash

var obj = { 
  a: 1,
  b: { 
    c: 2
  }
}

var newObj = _.cloneDeep(obj);
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } } 

4.使用Object.assign()方法

var obj = { 
  a: 1,
  b: 2
}

var newObj = _.clone(obj);
obj.b = 20;
console.log(obj); // { a: 1, b: 20 }
console.log(newObj); // { a: 1, b: 2 }  

但是错误

var obj = { 
  a: 1,
  b: { 
    c: 2
  }
}

var newObj = Object.assign({}, obj);
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 20 } } --> WRONG
// Note: Properties on the prototype chain and non-enumerable properties cannot be copied.

5.采用Underscore.js _.clone链接Underscore.js

var obj = { 
  a: 1,
  b: 2
}

var newObj = _.clone(obj);
obj.b = 20;
console.log(obj); // { a: 1, b: 20 }
console.log(newObj); // { a: 1, b: 2 }  

但是错误

var obj = { 
  a: 1,
  b: { 
    c: 2
  }
}

var newObj = _.cloneDeep(obj);
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 20 } } --> WRONG
// (Create a shallow-copied clone of the provided plain object. Any nested objects or arrays will be copied by reference, not duplicated.)

JSBEN.CH性能基准测试场1〜3 http://jsben.ch/KVQLd 性能用JavaScript深度复制对象


#27楼

查看此基准测试: http : //jsben.ch/#/bWfk9

在以前的测试中,速度是最主要的问题,我发现

JSON.parse(JSON.stringify(obj))

是深度克隆对象的最慢方法(它比jQuery.extenddeep flag将true设置为10-20%慢)。

deep标志设置为false (浅克隆)时,jQuery.extend非常快。 这是一个很好的选择,因为它包括一些用于类型验证的额外逻辑,并且不会复制未定义的属性等,但这也会使您慢下来。

如果您知道要克隆的对象的结构,或者可以避免使用深层嵌套的数组,则可以在检查hasOwnProperty的同时编写一个简单的for (var i in obj)循环来克隆对象,它将比jQuery快得多。

最后,如果您尝试在热循环中克隆已知的对象结构,则只需内联克隆过程并手动构造对象,即可获得更多的性能。

JavaScript跟踪引擎在优化for..in循环中很for..in并且检查hasOwnProperty也会降低您的速度。 绝对必要时必须手动克隆。

var clonedObject = {
  knownProp: obj.knownProp,
  ..
}

当心在Date对象上使用JSON.parse(JSON.stringify(obj))方法JSON.stringify(new Date())以ISO格式返回JSON.stringify(new Date())的字符串表示形式, JSON.parse() 不会转换回Date对象。 有关更多详细信息,请参见此答案

此外,请注意,至少在Chrome 65中,本机克隆不是可行的方法。 根据JSPerf的说法,通过创建新功能执行本机克隆的速度比使用JSON.stringify的速度要快近800倍,而JSON.stringify的整个过程都非常快。

ES6更新

如果您使用的是Javascript ES6,请尝试使用本机方法进行克隆或浅拷贝。

Object.assign({}, obj);

#28楼

通常这不是最有效的解决方案,但它可以满足我的需求。 下面的简单测试用例...

function clone(obj, clones) {
    // Makes a deep copy of 'obj'. Handles cyclic structures by
    // tracking cloned obj's in the 'clones' parameter. Functions 
    // are included, but not cloned. Functions members are cloned.
    var new_obj,
        already_cloned,
        t = typeof obj,
        i = 0,
        l,
        pair; 

    clones = clones || [];

    if (obj === null) {
        return obj;
    }

    if (t === "object" || t === "function") {

        // check to see if we've already cloned obj
        for (i = 0, l = clones.length; i < l; i++) {
            pair = clones[i];
            if (pair[0] === obj) {
                already_cloned = pair[1];
                break;
            }
        }

        if (already_cloned) {
            return already_cloned; 
        } else {
            if (t === "object") { // create new object
                new_obj = new obj.constructor();
            } else { // Just use functions as is
                new_obj = obj;
            }

            clones.push([obj, new_obj]); // keep track of objects we've cloned

            for (key in obj) { // clone object members
                if (obj.hasOwnProperty(key)) {
                    new_obj[key] = clone(obj[key], clones);
                }
            }
        }
    }
    return new_obj || obj;
}

循环数组测试...

a = []
a.push("b", "c", a)
aa = clone(a)
aa === a //=> false
aa[2] === a //=> false
aa[2] === a[2] //=> false
aa[2] === aa //=> true

功能测试...

f = new Function
f.a = a
ff = clone(f)
ff === f //=> true
ff.a === a //=> false

#29楼

我知道这是一篇过时的文章,但是我认为这对下一个偶然发现的人可能会有帮助。

只要您不将对象分配给任何对象,它就不会在内存中保留任何引用。 因此,要创建一个要与其他对象共享的对象,就必须创建一个工厂,如下所示:

var a = function(){
    return {
        father:'zacharias'
    };
},
b = a(),
c = a();
c.father = 'johndoe';
alert(b.father);

#30楼

如果您使用它,则Underscore.js库具有克隆方法。

var newObject = _.clone(oldObject);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值