初探 Array.copyWithin()
前言
最近看到 Array.copyWithin() ,結果看 [ developer.mozilla.org ] Array.prototype.copyWithin() 多次後才看懂,Array.copyWithin() 的參數設置相當不直覺,在此把學習的過程做個紀錄。
內容
Array.copyWithin() 的功能是依據輸入的參數來複製 Array ,但要注意雖說是複製,事實卻是會把複製的結果改變到現在的 Array ,應用範例如下
let ar = [ 0 , 1 , 2 , 3 , 4 , 5 ];
console.log( [...ar].copyWithin( 0 , 0) );//[0, 1, 2, 3, 4, 5]
console.log( [...ar].copyWithin( 1 , 0) );//[0, 0, 1, 2, 3, 4]
console.log( [...ar].copyWithin( 2 , 0) );//[0, 1, 0, 1, 2, 3]
console.log( [...ar].copyWithin( 3 , 0) );//[0, 1, 2, 0, 1, 2]
console.log( [...ar].copyWithin( 4 , 0) );//[0, 1, 2, 3, 0, 1]
console.log( [...ar].copyWithin( 5 , 0) );//[0, 1, 2, 3, 4, 0]
console.log( [...ar].copyWithin( 6 , 0) );//[0, 1, 2, 3, 4, 5]
//
console.log( [...ar].copyWithin( 2 , 1) );//[0, 1, 1, 2, 3, 4]
console.log( [...ar].copyWithin( 3 , 1) );//[0, 1, 2, 1, 2, 3]
Array.copyWithin() 的參數有兩個,分別是 index 與 start ,index 表示要從哪個目標 Array 索引開始複製,start 則表示要從來源 Array 的哪個索引開始複製。以範例的第一例來看是從目標的索引 0 開始複製,來源是從索引 0 開始複製,所以第一例地所以值都是被來源 Array 複製,第二例的目表索引是 1 ,所以結果的索引0 不會被來源 Array 複製到,結果是從索引 1 開始從來源 Array 複製,接著依此類推,如果 index 大於原始 Array.length 的話此 Function 等於沒任何作用,可以看到範例的 copyWithin( 6 , 0) ,範例的最後兩例示範了改變 start 後結果會有什麼不一樣,可以分別跟 copyWithin( 2, 0) 與 copyWithin( 3 , 0) 拿來對比。再次提醒,所說這個 Function 的功能是複製,但這個 Funciton 會改變原本 Funcitton 的值,所以範例都是複製 ar 陣列後才喚起 Array.copyWithin()。
參考資料
[ developer.mozilla.org ] Array.prototype.copyWithin()