最近在複習JS的時候,常對一些長得很像的東西感到困擾 @~@
像是等等要介紹的S三姐妹 split( )
、 slice( )
、splice( )
這三個真的有點像在玩文字遊戲啊!!!!不過各自還是有點差別的,那就來一一破解吧
The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
1-1 解釋:split()
把原字串依照指定的符號分割成子字串,並放入陣列中回傳
1-2 特點:
1-3 語法:
本圖擷取自MDN
1-4 示範:
/*split()*/
let str = "Happy day Happy life."
let arr = str.split(" ") //以"空格"分割字串
console.log(arr); /*["Happy","day","Happy","life."]*/
arr = str.split(" ",0)
console.log(arr);/*[]*/
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
2-1 解釋:
slice在中文中有切片的意思,slice()
可以想像成從哪裡開始去切,會回傳一個新的陣列,為原陣列 start 至 end(不含 end)部分的淺拷貝(shallow copy),而原本的陣列並不會被修改
2-2 語法:
本圖擷取自MDN
2-3 特點:
2-4 示範:
/*slice()*/
let arr2 = ["I","have","to","sleep","It\'s","1:25","a.m."]
console.log(arr2.slice(5)); /*["1:25","a.m."]*/
console.log(arr2.slice(1,-1)) /*["have","to","sleep","It's","1:25"]*/
console.log(arr2.slice(1,7)) /*["have","to","sleep","It's","1:25","a.m."]*/
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place(原地演算法).
3-1 解釋:splice()
可以透過移除(removing)、替換(replacing)或是新增(adding)元素的方式來改變陣列的內容
3-2 語法:
本圖擷取自MDN
3-3 特點:
3-4 示範:
/*splice()*/
const season = ['spring', 'summer', 'winter'];
season.splice(2, 0, 'autumn');
//從第二個開始 刪除0個 增加autumn
console.log(season); //["spring","summer","autumn","winter"]
season.splice(3,1,'Hello Winter');
console.log(season);
/* ["spring","summer","autumn","Hello Winter"]*/
方法 | 說明 |
---|---|
split(separator,limit) |
字串處理方法,回傳一個陣列 |
slice(start,end) |
陣列處理方法,回傳一個新的陣列 |
splice(start,deleteCount,itim...) |
陣列處理方法,回傳一個陣列(我都想像成原陣列的Before/After) |
以上是我自己的學習筆記,除了日後可以給自己看,也希望能幫助到有需要的人^ ^ 所學不精,若有解說不詳盡、錯誤之處歡迎指教,阿哩嘎都
MDN-split()
MDN-splice()
MDN-slice()
深拷貝與淺拷貝