首頁  >  文章  >  web前端  >  JavaScript 中物件的深拷貝

JavaScript 中物件的深拷貝

黄舟
黄舟原創
2016-12-14 09:59:411083瀏覽

物件的深拷貝與淺拷貝的區別如下:

淺拷貝:僅複製物件的引用,而不是物件本身;
深拷貝:把複製的物件所引用的全部物件都複製一遍。

一. 淺拷貝的實作

淺拷貝的實作方法比較簡單,只要使用是簡單的複製語句即可。

1.1 方法一:簡單的複製語句

/* ================ 浅拷贝 ================ */
function simpleClone(initalObj) {
    var obj = {};
    for ( var i in initalObj) {
        obj[i] = initalObj[i];
    }
    return obj;
}

   

客戶端呼叫

/* ================ 客户端调用 ================ */
var obj = {
    a: "hello",
    b: {
        a: "world",
        b: 21
    },
    c: ["Bob", "Tom", "Jenny"],
    d: function() {
        alert("hello world");
    }
}
var cloneObj = simpleClone(obj); // 对象拷贝
   
console.log(cloneObj.b); // {a: "world", b: 21}
console.log(cloneObj.c); // ["Bob", "Tom", "Jenny"]
console.log(cloneObj.d); // function() { alert("hello world"); }
   
// 修改拷贝后的对象
cloneObj.b.a = "changed";
cloneObj.c = [1, 2, 3];
cloneObj.d = function() { alert("changed"); };
   
console.log(obj.b); // {a: "changed", b: 21} // // 原对象所引用的对象被修改了
   
console.log(obj.c); // ["Bob", "Tom", "Jenny"] // 原对象所引用的对象未被修改
console.log(obj.d); // function() { alert("hello world"); } // 原对象所引用的函数未被修改

1.2 方法二碼自身的可列舉屬性拷貝給目標對象,然後返回目標對象。但是 Object.assign() 進行的是淺拷貝,拷貝的是物件的屬性的引用,而不是物件本身。

 
var obj = { a: {a: "hello", b: 21} }; 
var initalObj = Object.assign({}, obj); 
initalObj.a.a = "changed"; 
console.log(obj.a.a); // "changed"

二. 深拷貝的實作

要實現深拷貝有很多辦法,有最簡單的 JSON.parse() 方法,也有常用的遞歸拷貝方法,和ES5中的 Object.create() 方法。

2.1 方法一:使用 JSON.parse() 方法

要實現深拷貝有很多方法,例如最簡單的方法是使用 JSON.parse():

/* ================ 深拷贝 ================ */
function deepClone(initalObj) {
    var obj = {};
    try {
        obj = JSON.parse(JSON.stringify(initalObj));
    }
    return obj;
}
    
/* ================ 客户端调用 ================ */
var obj = {
    a: {
        a: "world",
        b: 21
    }
}
var cloneObj = deepClone(obj);
cloneObj.a.a = "changed";
   
console.log(obj.a.a); // "world"

   

易用這種方法。

但是這種方法也有不少壞處,譬如它會拋棄對象的constructor。也就是深拷貝之後,不管這個物件原來的建構子是什麼,在深拷貝之後都會變成Object。

這種方法能正確處理的對像只有 Number, String, Boolean, Array, 扁平對象,即那些能夠被 json 直接表示的資料結構。 RegExp物件是無法以這種方式深拷貝。

2.2 方法二:遞迴拷貝

程式碼如下:

/* ================ 深拷贝 ================ */
function deepClone(initalObj, finalObj) {
    var obj = finalObj || {};
    for (var i in initalObj) {
        if (typeof initalObj[i] === 'object') {
            obj[i] = (initalObj[i].constructor === Array) ? [] : {};
            arguments.callee(initalObj[i], obj[i]);
        } else {
            obj[i] = initalObj[i];
        }
    }
    return obj;
}

   

上述程式碼確實可以實現深拷貝。但是當遇到兩個互相引用的對象,就會出現死循環的情況。

為了避免相互引用的對象導致死循環的情況,則應該在遍歷的時候判斷是否相互引用對象,如果是則退出循環。

改進版程式碼如下:

/* ================ 深拷贝 ================ */
function deepClone(initalObj, finalObj) {
    var obj = finalObj || {};
    for (var i in initalObj) {
        var prop = initalObj[i];
   
        // 避免相互引用对象导致死循环,如initalObj.a = initalObj的情况
        if(prop === obj) {
            continue;
        }
   
        if (typeof prop === 'object') {
            obj[i] = (prop.constructor === Array) ? [] : {};
            arguments.callee(prop, obj[i]);
        } else {
            obj[i] = prop;
        }
    }
    return obj;
}

   

2.3 方法三:使用Object.create()方法

直接使用var newObj = Object.create(oldObj),可以達到深拷貝的效果。

/* ================ 深拷贝 ================ */
function deepClone(initalObj, finalObj) {
    var obj = finalObj || {};
    for (var i in initalObj) {
        var prop = initalObj[i];
   
        // 避免相互引用对象导致死循环,如initalObj.a = initalObj的情况
        if(prop === obj) {
            continue;
        }
   
        if (typeof prop === 'object') {
            obj[i] = (prop.constructor === Array) ? [] : Object.create(prop);
        } else {
            obj[i] = prop;
        }
    }
    return obj;
}

   

三.參考:jQuery.extend()方法的實作

jQuery.js的jQuery.extend()也實作了物件的深拷貝。以下將官方程式碼貼出來,以供參考。

官方連結網址:https://github.com/jquery/jquery/blob/master/src/core.js。

jQuery.extend = jQuery.fn.extend = function() {
    var options, name, src, copy, copyIsArray, clone,
        target = arguments[ 0 ] || {},
        i = 1,
        length = arguments.length,
        deep = false;
   
    // Handle a deep copy situation
    if ( typeof target === "boolean" ) {
        deep = target;
   
        // Skip the boolean and the target
        target = arguments[ i ] || {};
        i++;
    }
   
    // Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
        target = {};
    }
   
    // Extend jQuery itself if only one argument is passed
    if ( i === length ) {
        target = this;
        i--;
    }
   
    for ( ; i < length; i++ ) {
   
        // Only deal with non-null/undefined values
        if ( ( options = arguments[ i ] ) != null ) {
   
            // Extend the base object
            for ( name in options ) {
                src = target[ name ];
                copy = options[ name ];
   
                // Prevent never-ending loop
                if ( target === copy ) {
                    continue;
                }
   
                // Recurse if we&#39;re merging plain objects or arrays
                if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
                    ( copyIsArray = jQuery.isArray( copy ) ) ) ) {
   
                    if ( copyIsArray ) {
                        copyIsArray = false;
                        clone = src && jQuery.isArray( src ) ? src : [];
   
                    } else {
                        clone = src && jQuery.isPlainObject( src ) ? src : {};
                    }
   
                    // Never move original objects, clone them
                    target[ name ] = jQuery.extend( deep, clone, copy );
   
                // Don&#39;t bring in undefined values
                } else if ( copy !== undefined ) {
                    target[ name ] = copy;
                }
            }
        }
    }
   
    // Return the modified object
    return target;
};

   

這篇文章主要是介紹js關於深拷貝的內容,其它的內容可以查看PHP中文網(www.php.cn)的文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn