js陣列物件複製拷貝不改變原來的值,深拷貝
js陣列,物件複製拷貝,深拷貝,按值傳遞
陣列拷貝
方法1
es6擴充套件運算子
let arr1 = [1, 2, 3],
arr2 = [...arr1];
arr2.pop();
console.log(arr1);
console.log(arr2);
2Object.assign()
let arr1 = [1, 2, 3],
arr2 = [];
Object.assign(arr2,arr1)
arr2.pop();
console.log(arr1);
console.log(arr2);
> Array [1, 2, 3]
> Array [1, 2]
3 concat
let arr1 = [1, 2, 3],
arr2 = arr1.concat();
arr2.pop();
console.log(arr1);
console.log(arr2);
4Array.form
let arr1 = [1, 2, 3],
arr2 = Array.from(arr1);
arr2.splice(0, 1);
console.log(arr1);
console.log(arr2);
5 push.apply
let arr1 = [1, 2, 3],
arr2 = [];
arr2.push.apply(arr2, arr1);
arr2.pop();
console.log(arr1);
console.log(arr2);
6 slice
let arr1 = [1, 2, 3],
arr2 = arr1.slice();
arr2.pop();
console.log(arr1);
console.log(arr2);
7 json
let arr1 = [1, 2, 3],
arr2 = JSON.parse(JSON.stringify(arr1));
arr2.pop();
console.log(arr1);
console.log(arr2);
物件拷貝
let a = {name : "liming",
id :1},
b = Object.assign({},a);
b.id = 2;
console.log(a);
console.log(b);
> Object { name: "liming", id: 1 }
> Object { name: "liming", id: 2 }
陣列中有物件
let a = [1,2,3,{name : "liming",
id :1}],
b = JSON.parse(JSON.stringify(a));
b[3].id = 2;
console.log(a);
console.log(b);
> Array [1, 2, 3, Object { name: "liming", id: 1 }]
> Array [1, 2, 3, Object { name: "liming", id: 2 }]
相關文章
- js 陣列的淺拷貝和深拷貝JS陣列
- js 淺拷貝(淺複製、淺克隆)、深拷貝(深複製、深克隆)JS
- Vue實現對陣列、物件的深拷貝、複製Vue陣列物件
- [分享]javascript 陣列以及物件的深拷貝(複製陣列或複製物件)的方法JavaScript陣列物件
- 物件深拷貝和淺拷貝物件
- 物件的深拷貝與淺拷貝物件
- JS深拷貝與淺拷貝JS
- js 淺拷貝和深拷貝JS
- js 深拷貝和淺拷貝JS
- js深拷貝和淺拷貝JS
- js 深拷貝 vs 淺拷貝JS
- js的深拷貝和淺拷貝JS
- 賦值、淺拷貝與深拷貝賦值
- 實現物件淺拷貝、深拷貝物件
- 聊聊物件深拷貝和淺拷貝物件
- 【JavaScript】物件的淺拷貝與深拷貝JavaScript物件
- Python - 物件賦值、淺拷貝、深拷貝的區別Python物件賦值
- jquery之物件拷貝深拷貝淺拷貝案例講解jQuery物件
- 【JS】深拷貝與淺拷貝,實現深拷貝的幾種方法JS
- js之淺拷貝和深拷貝JS
- js資料型別賦值,淺拷貝,深拷貝JS資料型別賦值
- JavaScript物件的深拷貝以及淺拷貝分析JavaScript物件
- 陣列和物件的拷貝陣列物件
- PHP 物件導向 - 物件的淺拷貝與深拷貝PHP物件
- 理解JS中的淺拷貝與深拷貝JS
- js實現深拷貝和淺拷貝JS
- 淺探js深拷貝和淺拷貝JS
- vue深拷貝淺拷貝Vue
- [JS系列二]談談深拷貝和淺拷貝,如何實現深拷貝JS
- JS複習之深淺拷貝JS
- js物件實現深淺拷貝!!JS物件
- js深拷貝方法JS
- js 深拷貝方法JS
- 淺談深拷貝與淺拷貝?深拷貝幾種方法。
- 淺析賦值、淺拷貝、深拷貝的區別賦值
- 【Python】直接賦值,深拷貝和淺拷貝Python賦值
- iOS深拷貝和淺拷貝iOS
- Java深拷貝和淺拷貝Java