技巧 7 - 使用解构
- const numbers = [1, 2, 3, 4, 5];
-
- const [...copy] = numbers;
- copy.push(6); // 添加新项以证明不会修改原始数组
-
- console.log(copy);
- console.log(numbers);
-
- // 输出
- // [1, 2, 3, 4, 5, 6]
- // [1, 2, 3, 4, 5]
技巧 8 - 使用 Array.concat 方法
- const numbers = [1, 2, 3, 4, 5];
-
- const copy = numbers.concat();
- copy.push(6); // 添加新项以证明不会修改原始数组
-
- console.log(copy);
- console.log(numbers);
-
- // 输出
- // [1, 2, 3, 4, 5, 6]
- // [1, 2, 3, 4, 5]
技巧 9 - 使用 `Array.push` 方法和展开操作符
- const numbers = [1, 2, 3, 4, 5];
-
- let copy = [];
- copy.push(...numbers);
- copy.push(6); // 添加新项以证明不会修改原始数组
-
- console.log(copy);
- console.log(numbers);
-
- // 输出
- // [1, 2, 3, 4, 5, 6]
- // [1, 2, 3, 4, 5]
技巧 10 - 使用 `Array.unshift ` 方法和展开操作符
- const numbers = [1, 2, 3, 4, 5];
-
- let copy = [];
- copy.unshift(...numbers);
- copy.push(6); // 添加新项以证明不会修改原始数组
-
- console.log(copy);
- console.log(numbers);
-
- // 输出
- // [1, 2, 3, 4, 5, 6]
- // [1, 2, 3, 4, 5]
技巧 11 - 使用 `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);
-
- // 输出
- // [1, 2, 3, 4, 5, 6]
- // [1, 2, 3, 4, 5]
(编辑:西安站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|