溫馨提示×

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

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

javascript深拷貝的方法有哪些

發(fā)布時(shí)間:2020-06-01 20:46:43 來源:億速云 閱讀:285 作者:鴿子 欄目:web開發(fā)

1、將對(duì)象轉(zhuǎn)換為JSON字符串形式,再將其轉(zhuǎn)換為原生JS對(duì)象;

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

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

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

2、使用JS中的for循環(huán)實(shí)現(xiàn)遍歷和復(fù)制;

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]);//如果對(duì)象的屬性值為object的時(shí)候,遞歸調(diào)用deepClone,即在吧某個(gè)值對(duì)象復(fù)制一份到新的對(duì)象的對(duì)應(yīng)值中。
            } else {
                result[key] = obj[key];//如果對(duì)象的屬性值不為object的時(shí)候,直接復(fù)制參數(shù)對(duì)象的每一個(gè)鍵值到新的對(duì)象對(duì)應(yīng)的鍵值對(duì)中。
            }

        }
        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、利用數(shù)組的“Array.prototype.forEach”方法進(jìn)行復(fù)制即可實(shí)現(xiàn)深拷貝。

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 深拷貝的三種實(shí)現(xiàn)方式的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注億速云其它相關(guān)文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI