Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #### Splice(拼接) vs Slice(切片)
- - `splice()`: 原陣列會被修改,第二個參數代表要刪除的元素個數,之後的可選參數,代表要替補被刪除位置的元素。
- ```js
- var months = ['Jan', 'March', 'April', 'June'];
- months.splice(1, 0, 'Feb');
- // inserts at index 1
- console.log(months);
- // expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']
- months.splice(4, 1, 'May');
- // replaces 1 element at index 4
- console.log(months);
- // expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']
- ```
- - `slice()`: 不修改原陣列,按照參數複製一個新陣列,參數代表複製的起點及終點索引(省略則代表到末尾),但`終點索引`的位置不包含在內。
- ```js
- var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
- console.log(animals.slice(2));
- // expected output: Array ["camel", "duck", "elephant"]
- console.log(animals.slice(2, 4));
- // expected output: Array ["camel", "duck"]
- console.log(animals.slice(1, 5));
- // expected output: Array ["bison", "camel", "duck", "elephant"]
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement