2025年5月5日 星期一

再探 Array.copyWithin()

 再探 Array.copyWithin()

前言

  在先前的 初探 Array.copyWithin() 裡基本的使用了 Array.copyWithin() 。範例使用 Array.copyWithin() 時都使用兩個引數,但 Array.copyWithin()  還可以使用三個引數,在此把學習的過程做個紀錄。


內容

  Array.copyWithin() 使用三個引數時會比兩個引數多出一個 end 的引數,該引數放在最後,配合第二個引數 start 來使用,start 表示要從來源 Array 的哪個索引開始複製, end 表示複製到來源 Array的那個索引為止,使用的範例如下

let ar = [ 0 , 1 , 2 , 3 , 4 , 5 ];
//
console.log( [...ar].copyWithin( 1 , 0 ) );//[0, 0, 1, 2, 3, 4]
console.log( [...ar].copyWithin( 1 , 0 , ar.length) );//[0, 0, 1, 2, 3, 4]
console.log( [...ar].copyWithin( 1 , 0 , 3) );//[0, 0, 1, 2, 4, 5]
console.log( [...ar].copyWithin( 3 , 1 , 2) );//[0, 1, 2, 1, 4, 5]
console.log( [...ar].copyWithin( 3 , 1 , 1) );//[0, 1, 2, 3, 4, 5]


end 控制的是要複製到的索引,所以如果 end 填上陣列的數量的結果就跟只使用兩個引數的結果一樣,可以在範例的第一例與第二例看到。第三例有設置 end 為 3 ,所以結果看到索引 1~3 是被限制的 copy ,索引 4~5 則保持原來的值。要注意的是 end 並不是表示數量,也和 start 一樣是索引,第四例的 start 與 end 只差 1 ,所以結果只改變了索引 3 ,如果把 start 與 end 填成一樣的,就會發現不會有任何的值被改變,就像第五例那樣。


參考資料

[ developer.mozilla.org ] Array.prototype.copyWithin()


相關文章與資料

初探 Array.copyWithin()

沒有留言:

張貼留言