让前端飞Web前端之路JavaScript 进阶营

javascript总结:深拷贝与浅拷贝的实现

2019-08-08  本文已影响17人  张培跃
1、浅拷贝实现

原对象

const obj = {
    siteName:"张培跃",
    info:{
        age:18,
        props:["阳光","帅气"]
    }
}
// 1. ...实现
let copy1 = {...obj};
console.log(copy1 === obj);// false
console.log(copy1.info === obj.info);// true
console.log(copy1.siteName);// 张培跃

// 2. Object.assign实现
let copy2 = Object.assign({},obj);
console.log(copy2 === obj);// false
console.log(copy2.info === obj.info);// true
console.log(copy2.siteName);// 张培跃

// 3、for in 实现
let copy3 = {};
for(let key in obj){
    copy3[key] = obj[key];
}
console.log(copy2 === obj);// false
console.log(copy2.info === obj.info);// true
console.log(copy2.siteName);// 张培跃

原数组

const arr =[{
    siteName:"张培跃",
    info:{
        age:18,
        props:["阳光","帅气"]
    }
}]
// 1. ...实现
let copy1 = {...arr};
console.log(copy1 === arr);// false
console.log(copy1[0].info === arr[0].info);// true
console.log(copy1[0].siteName);// 张培跃

// 2. Array.from实现
let copy2 = Array.from(arr);
console.log(copy2 === arr);// false
console.log(copy2[0].info === arr[0].info);// true
console.log(copy2[0].siteName);// 张培跃

// 3、forEach实现
let copy3 = [];
arr.forEach(v=>copy3.push(v));
copy3 = Array.from(arr);
console.log(copy3 === arr);// false
console.log(copy3[0].info === arr[0].info);// true
console.log(copy3[0].siteName);// 张培跃

// 4、map实现
let copy4 = arr.map(v=>v);
console.log(copy4 === arr);// false
console.log(copy4[0].info === arr[0].info);// true
console.log(copy4[0].siteName);// 张培跃
2、深拷贝实现
const obj = {
    siteName:"张培跃",
    info:{
        age:18,
        props:["阳光","帅气"]
    }
}
const copy1 = JSON.parse(JSON.stringify(obj));
console.log(copy1 === obj);// false
console.log(copy1.info === obj.info);// false
console.log(copy1.info.props === obj.info.props);// false
console.log(copy1.siteName);// 张培跃
function deepClone(obj) {
    // 判断是否数组或对象,确定初始值
    let copy = obj instanceof Array ? [] : {}
    for (let i in obj) {
        if (obj.hasOwnProperty(i)) {
            copy[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
        }
    }
    return copy
}
const obj = {
    siteName:"张培跃",
    info:{
        age:18,
        props:["阳光","帅气"]
    }
}
const copy1 = deepClone(obj);
console.log(copy1 === obj);// false
console.log(copy1.info === obj.info);// false
console.log(copy1.info.props === obj.info.props);// false
console.log(copy1.siteName);// 张培跃

—————END—————
喜欢本文的朋友们,欢迎关注公众号 张培跃,收看更多精彩内容!!!公众号回复 电子书 ,送你经典电子书籍!

上一篇 下一篇

猜你喜欢

热点阅读