赞
踩
使用 = 直接赋值数组,修改新数组时会把原数组修改掉:
- let oldArr = [
- {group: 1, id: 2, name: "aa"},
- {group: 2, id: 1, name: "bb"}];
- let newArr2 = oldArr;
- for (let i = 0; i < newArr2.length; i++) {
- if (newArr2[i].id == 1) {
- newArr2[i].name = "new";
- break;
- }
- }
- console.log(oldArr);
- console.log(newArr2);
使用对象深拷贝,修改数组不影响原数组:
- let oldArr = [
- {group: 1, id: 2, name: "aa"},
- {group: 2, id: 1, name: "bb"}];
-
-
- let newArr2 = JSON.parse(JSON.stringify(oldArr)); //对象深拷贝,修改不影响之前的
- for (let i = 0; i < newArr2.length; i++) {
- if (newArr2[i].id == 1) {
- newArr2[i].name = "new";
- break;
- }
- }
- console.log(oldArr);
- console.log(newArr2);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。