深拷贝和浅拷贝

参考:js 数组和对象深拷贝的方法 https://www.cnblogs.com/webSnow/p/16134946.html

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript 数组</h1>

<p>请单击按钮,以使用负数参数提取第三个和第四个元素。</p>

<button onclick="myFunction()">试一试</button>

<p id="demo1">P1</p>
<p id="demo2">P2</p>
<p id="demo3">P3</p>
<p id="demo4">P4</p>
<p id="demo5">P5</p>

<script>
function myFunction() {
  //var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
  //var myBest = fruits.slice(0);
  //var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
  var obj ={name:'jack', age:'30' }
  var arr1=[];
  arr1.push(obj);//1.数组1
  var [ ...arr2 ] = arr1;//数组2(深拷贝,对象数组不行)
  arr2[0].name ='peter';
  var arr3 = arr1.slice(0);//数组3(深拷贝,对象数组不行)
  arr3[0].name ='Tom';
  document.getElementById("demo1").innerHTML = 'P1=' +arr1[0].name;
  document.getElementById("demo2").innerHTML = 'P2=' +arr2[0].name;
  document.getElementById("demo3").innerHTML = 'P3=' +arr3[0].name;
  
  var arr4 = JSON.parse(JSON.stringify(arr1));//数组4(深拷贝,对象数组也可以)
  arr4[0].name ='haha';
  document.getElementById("demo4").innerHTML = 'P4=' +arr4[0].name;  
  
  var arr5 = copyObj(arr1);//数组4(深拷贝,对象数组也可以)
  arr5[0].name ='gold';
  document.getElementById("demo5").innerHTML = 'P4=' +arr5[0].name;
}
//对象数组深拷贝
function copyObj(obj) {
  let res = {}
  for (var key in obj) {
    res[key] = obj[key]
  }
  return res
}
</script>

</body>
</html>
posted @ 2022-12-20 13:22  朕在coding  阅读(12)  评论(0编辑  收藏  举报