头图

Of course, shallow copy can only be achieved for nested objects, and single-layer objects can achieve deep copy.

Method One Object.assign()

let target = {};
let source = {
    a:'123',
    b:{
        name:'zhang'
    }
}
Object.assign(target,source)
console.log(target); //{ a: '123', b: { name: 'zhang' } }
//修改嵌套对象b里面的属性
target.b.name = 'lisi';
console.log(source);  //{ a: '123', b: { name: 'lisi' } }

Method two Array.prototype.slice()

let array = [{a:1},{b:2}]
//slice() 方法选择从给定的 start 参数开始的元素,并在给定的 end 参数处结束,但不包括
let newArr = array.slice(0,2)
console.log(newArr);  //[ { a: 1 }, { b: 2 } ]
newArr[1].b = '222222'
console.log(array); //[ { a: 1 }, { b: '222222' } ]

Method three Array.prototype.concat()

let arrThird = [{c:1},{d:2}];
//concat()方法用于连接两个或多个数组,而是返回一个新数组,其中包含已连接数组的值
let newThird = [].concat(arrThird);
console.log(newThird);  //[ { c: 1 }, { d: 2 } ]
//修改新数组中newThird的c属性
newThird[0].c = '巴啦啦能量'
console.log(arrThird);  //[ { c: '巴啦啦能量' }, { d: 2 } ]

Method four extended operator...

let obj1 = {j:1,k:{i:2}}
//解构
let newObj = {...obj1}
console.log(newObj);  //{ j: 1, k: { i: 2 } }
newObj.j = '奥特曼'
console.log(obj1); //{ j: 1, k: { i: 2 } }
newObj.k.i = '小怪兽'
console.log(obj1); //{ j: 1, k: { i: '小怪兽' } }
//由此可知 浅拷贝是针对于嵌套对象来实现的

Method 5 Directly use = assignment

let a = [2,32,13,4]
let b = a;  //赋值操作
console.log(b); //[ 2, 32, 13, 4 ]
//修改b数组
b[1] = 'hell javaScript'
console.log(a); //[ 2, 'hell javaScript', 13, 4 ]

Method 6 for..in..

let obj = {a:{name:'小蓝',age:18}}

let copy = (obj) =>{
    let newObj = {}
    for(var key in obj){
        newObj[key] = obj[key]
    }
    return newObj
}
let objSix = copy(obj)
console.log(objSix); //{ a: { name: '小蓝', age: 18 } }
//修改 objSix 的属性
objSix.a.name = '游乐娃子'
console.log(obj); //{ a: { name: '游乐娃子', age: 18 } }

Method seven $.extend()

<!--
 * @Author: [you name]
 * @Date: 2021-10-29 10:25:55
 * @LastEditors: [you name]
 * @LastEditTime: 2021-10-31 10:30:27
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./1-jquery.3.6.0.js"></script>
    <script>
        // console.log($);

        //第七种  $.extend()
        let jObj1 = { a: { name: '泡芙', age: 18 } }
        let jObj2 = { b: { name: '可乐', age: 28 } }
        let jqObj = $.extend({},jObj1, jObj2)

        jqObj.a.name = '佟湘玉'
        console.log(jObj1); //a: {name: '佟湘玉', age: '18'}
        console.log(jObj2); //b: {name: '可乐', age: 28}
    </script>
</head>

<body>

</body>

</html>

云绮棠兮
48 声望10 粉丝

当野心追赶不上才华,便静下心来努力