Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. #### Splice(拼接) vs Slice(切片)
  2.  
  3. - `splice()`: 原陣列會被修改,第二個參數代表要刪除的元素個數,之後的可選參數,代表要替補被刪除位置的元素。
  4.  
  5. ```js
  6. var months = ['Jan', 'March', 'April', 'June'];
  7. months.splice(1, 0, 'Feb');
  8. // inserts at index 1
  9. console.log(months);
  10. // expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']
  11.  
  12. months.splice(4, 1, 'May');
  13. // replaces 1 element at index 4
  14. console.log(months);
  15. // expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']
  16. ```
  17.  
  18. - `slice()`: 不修改原陣列,按照參數複製一個新陣列,參數代表複製的起點及終點索引(省略則代表到末尾),但`終點索引`的位置不包含在內。
  19.  
  20. ```js
  21. var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
  22.  
  23. console.log(animals.slice(2));
  24. // expected output: Array ["camel", "duck", "elephant"]
  25.  
  26. console.log(animals.slice(2, 4));
  27. // expected output: Array ["camel", "duck"]
  28.  
  29. console.log(animals.slice(1, 5));
  30. // expected output: Array ["bison", "camel", "duck", "elephant"]
  31. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement