溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

javascript深拷貝的方法有哪些

發布時間:2020-06-01 20:46:43 來源:億速云 閱讀:319 作者:鴿子 欄目:web開發

1、將對象轉換為JSON字符串形式,再將其轉換為原生JS對象;

//_tmp和result是相互獨立的,沒有任何聯系,有各自的存儲空間。
let deepClone = function (obj) {
    let _tmp = JSON.stringify(obj);//將對象轉換為json字符串形式
    let result = JSON.parse(_tmp);//將轉換而來的字符串轉換為原生js對象
    return result;
};

let obj1 = {
    weiqiujaun: {
        age: 20,
        class: 1502
    },
    liuxiaotian: {
        age: 21,
        class: 1501
    }
};

let test = deepClone(obj1);
console.log(test);

2、使用JS中的for循環實現遍歷和復制;

function deepClone(obj) {
    let result = typeof  obj.splice === "function" ? [] : {};
    if (obj && typeof obj === 'object') {
        for (let key in obj) {
            if (obj[key] && typeof obj[key] === 'object') {
                result[key] = deepClone(obj[key]);//如果對象的屬性值為object的時候,遞歸調用deepClone,即在吧某個值對象復制一份到新的對象的對應值中。
            } else {
                result[key] = obj[key];//如果對象的屬性值不為object的時候,直接復制參數對象的每一個鍵值到新的對象對應的鍵值對中。
            }

        }
        return result;
    }
    return obj;
}

let testArray = ["a", "b", "c", "d"];
let testRes = deepClone(testArray);
console.log(testRes);
console.log(typeof testRes[1]);

let testObj = {
    name: "weiqiujuan",
    sex: "girl",
    age: 22,
    favorite: "play",
    family: {brother: "son", mother: "haha", father: "heihei"}
};
let testRes2 = deepClone(testObj);
testRes2.family.brother = "weibo";
console.log(testRes2);

3、利用數組的“Array.prototype.forEach”方法進行復制即可實現深拷貝。

let deepClone = function (obj) {
    let copy = Object.create(Object.getPrototypeOf(obj));
    let propNames = Object.getOwnPropertyNames(obj);
    propNames.forEach(function (items) {
        let item = Object.getOwnPropertyDescriptor(obj, items);
        Object.defineProperty(copy, items, item);

    });
    return copy;
};

let testObj = {
    name: "weiqiujuan",
    sex: "girl",
    age: 22,
    favorite: "play",
    family: {brother: "wei", mother: "haha", father: "heihei"}
}
let testRes2 = deepClone(testObj);
console.log(testRes2);

以上就是JS 深拷貝的三種實現方式的詳細內容,更多請關注億速云其它相關文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女