1. 程式人生 > 其它 >ES5 深拷貝&淺拷貝

ES5 深拷貝&淺拷貝

淺拷貝

遍歷賦值

 
const student = {
    name: 'anjiyu',
    sex: 'female',
    studyInfo: {
        school: '河南大學',
        level: '本科',
        posi: '學士'
    }
}
function deepCopy(srcObj){
    const resObj = {};
    if(srcObj instanceof Array){
        resObj = [];
    }
    for(const key in srcObj){
        resObj[key] = srcObj[key];
    }
    return resObj;
}

const newStu = deepCopy(student);
newStu.studyInfo.school = '河大';
console.log(`老同學的資訊`,student);
/*
老同學的資訊 {
  name: 'anjiyu',
  sex: 'female',
  studyInfo: { school: '河大', level: '本科', posi: '學士' }
}
 */
console.log(`新同學的資訊`,newStu);
/*
新同學的資訊 {
  name: 'anjiyu',
  sex: 'female',
  studyInfo: { school: '河大', level: '本科', posi: '學士' }
}
*/


Object.create()

以傳入物件作為原型建立一個新物件,並返回。

 
const student = {
    name: 'anjiyu',
    sex: 'female',
    studyInfo: {
        school: '河南大學',
        level: '本科',
        posi: '學士'
    }
}

const newStu = Object.create(student);
newStu.studyInfo.school = '河大';
console.log(`老同學的資訊`,student);
/*
老同學的資訊 {
  name: 'anjiyu',
  sex: 'female',
  studyInfo: { school: '河大', level: '本科', posi: '學士' }
}
 */
console.log(`新同學的資訊`,newStu.__proto__);
/*
新同學的資訊 {
  name: 'anjiyu',
  sex: 'female',
  studyInfo: { school: '河大', level: '本科', posi: '學士' }
}
*/


深拷貝

遞迴賦值

 
const student = {
    name: 'anjiyu',
    sex: 'female',
    studyInfo: {
        school: '河南大學',
        level: '本科',
        posi: '學士'
    }
}
function deepCopy(srcObj){
    const resObj = {};
    if(srcObj instanceof Array){
        resObj = [];
    }
    for(const key in srcObj){
        const value = srcObj[key];
        if(typeof value === 'object'){
            resObj[key] = deepCopy(value);
        }else{
            resObj[key] = value;
        }
    }
    return resObj;
}

const newStu = deepCopy(student);
newStu.studyInfo.school = '河大';
console.log(`老同學的資訊`,student);
/*
老同學的資訊 {
  name: 'anjiyu',
  sex: 'female',
  studyInfo: { school: '河南大學', level: '本科', posi: '學士' }
}
 */
console.log(`新同學的資訊`,newStu);
/*
新同學的資訊 {
  name: 'anjiyu',
  sex: 'female',
  studyInfo: { school: '河大', level: '本科', posi: '學士' }
}
*/


JSON.parse JSON.stringify

這種方法比較常用

 
const student = {
    name: 'anjiyu',
    sex: 'female',
    studyInfo: {
        school: '河南大學',
        level: '本科',
        posi: '學士'
    }
}

const newStu = JSON.parse(JSON.stringify(student));
newStu.studyInfo.school = '河大';
console.log(`老同學的資訊`,student);
/*
老同學的資訊 {
  name: 'anjiyu',
  sex: 'female',
  studyInfo: { school: '河南大學', level: '本科', posi: '學士' }
}
 */
console.log(`新同學的資訊`,newStu.__proto__);
/*
新同學的資訊 {
  name: 'anjiyu',
  sex: 'female',
  studyInfo: { school: '河大', level: '本科', posi: '學士' }
}
*/