js陣列物件複製拷貝不改變原來的值,深拷貝

flysnownet發表於2020-11-26

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 }]

 

相關文章