iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 12
0
自我挑戰組

JavaScript Array x 學習筆記系列 第 12

[Day 12 | Array.prototype.copyWithin () ]

array.copyWithin()

array.copyWithin() 是ES6新增的函數,

它可以複製自己本身的內容,再將複製的內容貼上(覆蓋)於自己的陣列內,
但是如果貼上後的內容超出原陣列的長度,超過的部份即會被省略

簡單的說,就是我們熟悉的
ctrl+c ctrl+v
但我理解好久 RRRR

注意 : 使用array.copyWithin()後,原陣列的內容會被改變


Syntax MDN - copyWithin

arr.copyWithin (target)

arr.copyWithin (target, start)

arr.copyWithin (target, start, end)
  • target - 要複製到索引值的位置。若為負數,target 將會自陣列末項開始計算。假如 target 大於等於 arr.length,則沒有項目會被複製。如果 target 的索引在 start 之後,則拷貝的序列將會被修剪以符合 arr.length。

  • start(選填) - 開始拷貝的起始位置,若為負數,start 將會自陣列末項開始計算。(預設為:0)

  • end(選填) - 結束拷貝的結尾元素索引(起始為 0)copyWithin 會拷貝至此索引,但不包含 end。若為負數,end 將會自陣列末項開始計算。

    如果省略 end,copyWithin 將會一路拷貝至陣列末項(預設至 arr.length)。


Example

程式碼如下:

const array1 = ['a', 'b', 'c', 'd', 'e'];
console.log(array1.copyWithin(3));
//將陣列拷貝一份,並從索引3的位置開始插入

const array2 = ['a', 'b', 'c', 'd', 'e'];
console.log(array2.copyWithin(3,1));
//將陣列拷貝一份(從索引1開始拷貝),並從索引3的位置插入

const array3 = ['a', 'b', 'c', 'd', 'e'];
console.log(array3.copyWithin(4, 1, 3));
//將陣列索引1~3(不包含3)拷貝,並從索引4的位置插入

參考來源 MDN


上一篇
[Day 11 | Array.prototype.sort () ]
下一篇
[Day 13 | Array.prototype.indexOf () - 簡易搜尋 ]
系列文
JavaScript Array x 學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言