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
- 物件深拷貝和淺拷貝物件
- Python - 物件賦值、淺拷貝、深拷貝的區別Python物件賦值
- js的深拷貝和淺拷貝JS
- js 淺拷貝和深拷貝JS
- JS深拷貝與淺拷貝JS
- js 深拷貝和淺拷貝JS
- 【JavaScript】物件的淺拷貝與深拷貝JavaScript物件
- 實現物件淺拷貝、深拷貝物件
- 聊聊物件深拷貝和淺拷貝物件
- 賦值、淺拷貝與深拷貝賦值
- 【JS】深拷貝與淺拷貝,實現深拷貝的幾種方法JS
- js之淺拷貝和深拷貝JS
- jquery之物件拷貝深拷貝淺拷貝案例講解jQuery物件
- js資料型別賦值,淺拷貝,深拷貝JS資料型別賦值
- JavaScript物件的深拷貝以及淺拷貝分析JavaScript物件
- 淺拷貝&深拷貝
- 理解JS中的淺拷貝與深拷貝JS
- PHP 物件導向 - 物件的淺拷貝與深拷貝PHP物件
- 淺探js深拷貝和淺拷貝JS
- js實現深拷貝和淺拷貝JS
- [JS系列二]談談深拷貝和淺拷貝,如何實現深拷貝JS
- js物件實現深淺拷貝!!JS物件
- 【Python】直接賦值,深拷貝和淺拷貝Python賦值
- JS複習之深淺拷貝JS
- 淺拷貝與深拷貝
- 淺拷貝和深拷貝
- 深拷貝和淺拷貝
- js 深拷貝方法JS
- js深拷貝方法JS
- JS中的深拷貝JS
- python 指標拷貝,淺拷貝和深拷貝Python指標
- 淺析賦值、淺拷貝、深拷貝的區別賦值
- 淺談深拷貝與淺拷貝?深拷貝幾種方法。
- 一文帶你瞭解js資料儲存及深複製(深拷貝)與淺複製(淺拷貝)JS
- Java深拷貝和淺拷貝Java
- Python淺拷貝與深拷貝Python