2025年5月19日 星期一

再探 Array.copyWithin() 之三

 再探 Array.copyWithin() 之三

前言

  在之前的 再探 Array.copyWithin() 之二 介紹當 target 的值是負值的狀況,這次來學習 start 的值是負值。


內容

  範例如下

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


當引數 start 是負值,代表複製的開頭索引是從結尾來算,第一例是 -1 ,所以最後只複製了一個,第二例是 -3 ,也就是複製倒數的三個,要注意順序依舊是 3,4,5 ,而不是 5,4,3。當沒有引數 end 的情況下。索引是負值可以解釋為要複製多少數量,所以當它是負的陣列大小時,等於複製全部陣列。


參考資料

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


相關文章與資料

再探 Array.copyWithin() 之二

再探 Array.copyWithin()

初探 Array.copyWithin()

沒有留言:

張貼留言