有几种方法可以复制一个数组。基本上,复制分为两种方式:
- 浅拷贝
- 深拷贝
浅拷贝仅仅覆盖了数组的第一层,其余部分都是引用。如果需要复制嵌套元素的真实副本,则需要进行深层克隆。
例如:
const arr1 = [1,2,3,4,5,6,7]
// Normal Array (shallow copy is enough)
const arr2 = [1,2,3,[4],[[5]],6,7]
// Nested Array (Deep copy required)
Approach 1 : Using (...)Spread Operator (Shallow copy enough)
const newArray = [...arr1] // [1,2,3,4,5,6,7]
Approach 2 : Using Array builtIn Slice method (Deep copy)
const newArray = arr1.slice() // [1,2,3,4,5,6,7]
Approach 3 : Using Array builtIn Concat method (Deep a copy)
const newArray = [].concat(arr1) // [1,2,3,4,5,6,7]
Approach 4 : Using JSON.stringify/parse. (Deep a copy & fastest)
const newArray = JSON.parse(JSON.stringify(arr2));) // [1,2,3,[4],[[5]],6,7]
Approach 5: Using own recursive function or using loadash's __.cloneDeep method. (Deep copy)
const getInitialArray = () => {return [[1, 2], [3, 4]}
- rybo111const getInitialArray = () => {return [[1, 2], [3, 4]}
- undefined