當前位置:
首頁 >
ES6,Array.copyWithin()函数的用法
發布時間:2025/3/15
25
豆豆
生活随笔
收集整理的這篇文章主要介紹了
ES6,Array.copyWithin()函数的用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ES6為Array增加了copyWithin函數,用于操作當前數組自身,用來把某些個位置的元素復制并覆蓋到其他位置上去。
Array.prototype.copyWithin(target, start = 0, end = this.length)該函數有三個參數。
target:目的起始位置。
start:復制源的起始位置,可以省略,可以是負數。
end:復制源的結束位置,可以省略,可以是負數,實際結束位置是end-1。
?
例:?
把第3個元素(從0開始)到第5個元素,復制并覆蓋到以第1個位置開始的地方。
下面的紅色塊是復制目標的起始位置,黃色塊為復制的源。
const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] arr1.copyWithin(1, 3, 6) console.log('%s', JSON.stringify(arr1))結果:
[1,4,5,6,5,6,7,8,9,10,11]?
start和end都是可以省略。
start省略表示從0開始,end省略表示數組的長度值。
目標的位置不夠的,能覆蓋多少就覆蓋多少。
const arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] arr2.copyWithin(3) console.log('%s', JSON.stringify(arr2))結果:
[1,2,3,1,2,3,4,5,6,7,8]?
start和end都可以是負數,負數表示從右邊數過來第幾個。
const arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] arr3.copyWithin(3, -3, -2) console.log('%s', JSON.stringify(arr3))結果:
[1,2,3,9,5,6,7,8,9,10,11]?
end
轉載于:https://www.cnblogs.com/kongxianghai/p/7527177.html
總結
以上是生活随笔為你收集整理的ES6,Array.copyWithin()函数的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring boot+mybatis
- 下一篇: pepflashplayer32_25_