當然,淺拷貝針對的是巢狀物件才能實現,單層物件實現的是深拷貝
方法一 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' } }
方法二 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' } ]
方法三 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 } ]
方法四 擴充運算子 ...
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: '小怪獸' } }
//由此可知 淺拷貝是針對於巢狀物件來實現的
方法五 直接用=賦值
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 ]
方法六 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 } }
方法七 $.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>