标签:console new concat 构造 共享 pre cat 技巧 const
当拷贝一个数组的时候,不能简单地将旧数组分配给一个新变量,如果这样做,它们将共享相同的引用,并且在更改一个变量之后,另一个变量也将受到更改的影响。下文将分享12个拷贝数组的技巧。
Array.slice
方法const arr = [1, 2, 3, 4, 5]
const copy = arr.slice()
copy.push(6) // 添加新项以证明不会修改原始数组
console.log(copy)
console.log(arr)
// 输出
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
Array.map
方法const arr = [1, 2, 3, 4, 5]
const copy = arr.map( num => num )
copy.push(6) // 添加新项以证明不会修改原始数组
console.log(copy);
console.log(arr);
// 输出
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
arr.filter()方法同理
Array.from
方法const arr = [1, 2, 3, 4, 5];
const copy = Array.from(new Set(arr));
copy.push(6); // 添加新项以证明不会修改原始数组
console.log(copy);
console.log(arr);
// 输出
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
注意set()方法有去重的效果,如果数组中有重复的数据得到的得到的新数组将会是去重后的数组
const arr = [1, 2, 3, 4, 5];
const copy = [...arr];
copy.push(6); // 添加新项以证明不会修改原始数组
console.log(copy);
console.log(arr);
// 输出
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
Array.of
方法和展开操作符const arr = [1, 2, 3, 4, 5];
const copy = Array.of(...arr);
copy.push(6); // 添加新项以证明不会修改原始数组
console.log(copy);
console.log(arr);
// 输出
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
const arr = [1, 2, 3, 4, 5];
const copy = new Array(...arr);
copy.push(6); // 添加新项以证明不会修改原始数组
console.log(copy);
console.log(arr);
// 输出
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
const arr = [1, 2, 3, 4, 5];
const [...copy] = arr;
copy.push(6); // 添加新项以证明不会修改原始数组
console.log(copy);
console.log(arr);
// 输出
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
const arr = [1, 2, 3, 4, 5];
const copy = arr.concat();
copy.push(6); // 添加新项以证明不会修改原始数组
console.log(copy);
console.log(arr);
// 输出
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
Array.push
方法和展开操作符const arr = [1, 2, 3, 4, 5];
let copy = [];
copy.push(...arr);
copy.push(6); // 添加新项以证明不会修改原始数组
console.log(copy);
console.log(arr);
// 输出
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
Array.unshift
方法和展开操作符const arr = [1, 2, 3, 4, 5];
let copy = [];
copy.unshift(...arr);
copy.push(6); // 添加新项以证明不会修改原始数组
console.log(copy);
console.log(arr);
// 输出
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
Array.forEach
方法和展开操作符const arr = [1, 2, 3, 4, 5];
let copy = [];
arr.forEach((value) => copy.push(value));
copy.push(6); // 添加新项以证明不会修改原始数组
console.log(copy);
console.log(arr);
// 输出
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
for
循环const arr = [1, 2, 3, 4, 5];
let copy = [];
for (let i = 0; i < arr.length; i++) {
copy.push(arr[i]);
}
copy.push(6); // 添加新项以证明不会修改原始数组
console.log(copy);
console.log(arr);
// 输出
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
标签:console new concat 构造 共享 pre cat 技巧 const
原文地址:https://www.cnblogs.com/cxyuan/p/11918216.html