2025年03月04日 建站教程
今天给大家介绍一下关于es6语法实现对象浅拷贝和深拷贝,下面小编给大家介绍一下代码!
利用Object.assign()实现浅拷贝
let target = {}; // 目标对象 let source = { a: 1 } // 原对象 Object.assign(target, source); console.log(target.a); // 1 source.a = 2; console.log(source.a); // 2 console.log(target.a); // 1
利用JSON.stringify()实现深拷贝
let target = {}; // 目标对象 let source = { a: 1, b: { d: 3 } } // 原对象 let targetStr = JSON.stringify(source); let target = JSON.parse(targetStr); console.log(target); // {a: 1, b: {d: 3}} source.b.d = 10; console.log(source); // {a: 1, b: {d: 10}} console.log(target); // {a: 1, b: {d: 3}}
本文链接:http://so.lmcjl.com/news/24279/