再探 Array.copyWithin() 之二
前言
在之前的 再探 Array.copyWithin() 介紹三個參數的用法,但查閱 [ developer.mozilla.org ] Array.prototype.copyWithin() 發現三個引數其實還可以輸入負值!這次先來學習引數 target 是負值的狀況。
內容
範例如下
let ar = [ 0 , 1 , 2 , 3 , 4 , 5 ]; // console.log( [...ar].copyWithin( -1 , 0 ) );//[0, 1, 2, 3, 4, 0] console.log( [...ar].copyWithin( -2 , 0 ) );//[0, 1, 2, 3, 0, 1] console.log( [...ar].copyWithin( -6 , 0 ) );//[0, 1, 2, 3, 4, 5]
當引數 target 是負值時,代表的是從陣列尾端倒過來指定,可以看到範例1 與 範例2 的結果是倒過來指定複製的位址,如果大於負陣列長度時,也就是範例3,這樣的結果就等於無作用,因為已經過了開頭了!
參考資料
[ developer.mozilla.org ] Array.prototype.copyWithin()
沒有留言:
張貼留言