| 
                         技巧 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] 
 
  
技巧 12 - 使用 `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); 
 -  
 - // 输出 
 - // [1, 2, 3, 4, 5, 6] 
 - // [1, 2, 3, 4, 5] 
 
  
技巧 13 - 使用 `Array.reduce` 方法 
这个做法是可行,但比较多余,少用 
- const numbers = [1, 2, 3, 4, 5]; 
 -  
 - const copy = numbers.reduce((acc, x) => { acc.push(x); return acc; }, []); 
 - copy.push(6); // 添加新项以证明不会修改原始数组 
 -  
 - console.log(copy); 
 - console.log(numbers); 
 -  
 - // 输出 
 - // [1, 2, 3, 4, 5, 6] 
 - // [1, 2, 3, 4, 5] 
 
  
技巧 14 - 使用古老的 `apply` 方法 
                        (编辑:52站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |