JavaScript拷贝数组
1.使用Array.slice
方法
1 | const numbers = [1, 2, 3, 4, 5]
|
2 |
|
3 | const copy = numbers.slice()
|
4 | copy.push(6);
|
5 |
|
6 | console.log(copy);
|
7 | console.log(numbers);
|
8 |
|
9 |
|
10 |
|
11 |
|
2. 使用Array.map
方法
1 | const numbers = [1, 2, 3, 4, 5]
|
2 |
|
3 | const copy = numbers.map( num => num )
|
4 | copy.push(6);
|
5 |
|
6 | console.log(copy);
|
7 | console.log(numbers);
|
8 |
|
9 |
|
10 |
|
11 |
|
3.使用Array.from
方法
1 | const numbers = [1, 2, 3, 4, 5];
|
2 |
|
3 | const copy = Array.from(new Set(numbers));
|
4 | copy.push(6);
|
5 |
|
6 | console.log(copy);
|
7 | console.log(numbers);
|
8 |
|
9 |
|
10 |
|
11 |
|
4.使用展开操作符
1 | const numbers = [1, 2, 3, 4, 5];
|
2 |
|
3 | const copy = [...numbers];
|
4 | copy.push(6);
|
5 |
|
6 | console.log(copy);
|
7 | console.log(numbers);
|
8 |
|
9 |
|
10 |
|
11 |
|
5.使用解构
1 | const numbers = [1, 2, 3, 4, 5];
|
2 |
|
3 | const [...copy] = numbers;
|
4 | copy.push(6);
|
5 |
|
6 | console.log(copy);
|
7 | console.log(numbers);
|
8 |
|
9 |
|
10 |
|
11 |
|
6. 使用 Array.concat
方法
1 | const numbers = [1, 2, 3, 4, 5];
|
2 |
|
3 | const copy = numbers.concat();
|
4 | copy.push(6);
|
5 |
|
6 | console.log(copy);
|
7 | console.log(numbers);
|
8 |
|
9 |
|
10 |
|
11 |
|