Быстрые примеры:
- Если элементы в массиве примитивных типов (строка, число и т. Д.)
var arr1 = ['a','b','c'];
// arr1 and arr2 are independent and primitive elements are stored in
// different places in the memory
var arr2 = arr1.slice();
arr2.push('d');
console.log(arr1); // [ 'a', 'b', 'c' ]
console.log(arr2); // [ 'a', 'b', 'c', 'd' ]
Если элементы в массиве являются
объектными литералами, другой массив ({}, []) var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
// arr1 and arr2 are independent and reference's/addresses are stored in different
// places in the memory. But those reference's/addresses points to some common place
// in the memory.
var arr2 = arr1.slice();
arr2.pop(); // OK - don't affect arr1 bcos only the address in the arr2 is
// deleted not the data pointed by that address
arr2[0].x = 'z'; // not OK - affect arr1 bcos changes made in the common area
// pointed by the addresses in both arr1 and arr2
arr2[1][0] = 9; // not OK - same above reason
console.log(arr1); // [ { x: 'z', y: 'b' }, [ 9, 2 ], [ 3, 4 ] ]
console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]
Решение для 2 : глубокое копирование от элемента к элементу
var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
arr2 = JSON.parse(JSON.stringify(arr1));
arr2.pop(); // OK - don't affect arr1
arr2[0].x = 'z'; // OK - don't affect arr1
arr2[1][0] = 9; // OK - don't affect arr1
console.log(arr1); // [ { x: 'a', y: 'b' }, [ 1, 2 ], [ 3, 4 ] ]
console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]