译者:王二狗
注意啦:点赞再看,养成习惯,你们的支持是我持续分享的最大动力(^▽^)
我们在克隆数组的时候,常常会犯这样的一个错误,仅仅把数组的值赋值给一个新的变量,如果我们做了这样的处理,则二者具有了相同的引用,其中一个如果发生了改变,另一个也会受其影响而发生变化,显然这样的结果并不是我们想得到的。
下面,我将分享给大家一些有趣的克隆数组的方式:
- 使用Array.slice方法
const numbers = [1, 2, 3, 4, 5];
const copy = numbers.slice();
copy.push(6);
// 通过添加一个数组项证明两个数组并非相同引用,下同
console.log(copy);
console.log(numbers);
// output
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
- 使用Array.map方法
const numbers = [1, 2, 3, 4, 5];
const copy = numbers.map(num => num);
copy.push(6);
console.log(copy);
console.log(numbers);
// output
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
- 使用Array.from方法
const numbers = [1, 2, 3, 4, 5];
const copy = Array.from(new Set(numbers));
copy.push(6);
console.log(copy);
console.log(numbers);
// output
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
- 使用扩展运算符
const numbers = [1, 2, 3, 4, 5];
const copy = [...numbers];
copy.push(6);
console.log(copy);
console.log(numbers);
// output
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
- 使用Array.of方法和扩展运算符
const numbers = [1, 2, 3, 4, 5];
const copy = Array.of(...numbers);
copy.push(6);
console.log(copy);
console.log(numbers);
// output
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
- 使用数组构造器和扩展运算符
const numbers = [1, 2, 3, 4, 5];
const copy = new Array(...numbers);
copy.push(6);
console.log(copy);
console.log(numbers);
// output
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
- 使用数组解构赋值
const numbers = [1, 2, 3, 4, 5];
const [...copy] = numbers;
copy.push(6);
console.log(copy);
console.log(numbers);
// output
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
- 使用Array.concat方法
const numbers = [1, 2, 3, 4, 5];
const copy = numbers.concat();
copy.push(6);
console.log(copy);
console.log(numbers);
// output
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
- 使用Array.push方法和扩展运算符
const numbers = [1, 2, 3, 4, 5];
let copy = [];
copy.push(...numbers);
copy.push(6); // add a new item to prove that we WILL NOT MODIFY the original array
console.log(copy);
console.log(numbers);
// output
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
- 使用Array.unshift方法和扩展运算符
const numbers = [1, 2, 3, 4, 5];
let copy = [];
copy.unshift(...numbers);
copy.push(6);
console.log(copy);
console.log(numbers);
// output
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
- 使用Array.forEach方法
const numbers = [1, 2, 3, 4, 5];
let copy = [];
numbers.forEach((value) => copy.push(value));
copy.push(6);
console.log(copy);
console.log(numbers);
// output
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
- 使用for循环
const numbers = [1, 2, 3, 4, 5];
let copy = [];
for (let i = 0; i < numbers.length; i++) {
copy.push(numbers[i]);
}
copy.push(6);
console.log(copy);
console.log(numbers);
// output
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
- 使用apply方法
const numbers = [1, 2, 3, 4, 5];
let copy = [];
Array.prototype.push.apply(copy, numbers);
copy.push(6);
console.log(copy);
console.log(numbers);
// output
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
告诫自己,即使再累也不要忘记学习,成功没有捷径可走,只有一步接着一步走下去。 共勉!
原文链接: devinduct.com/blogpost/50…