首頁  >  文章  >  web前端  >  ES6中Array.copyWithin()函數用法的詳解

ES6中Array.copyWithin()函數用法的詳解

巴扎黑
巴扎黑原創
2017-09-18 09:27:272142瀏覽

ES6為Array增加了copyWithin函數,用於操作當前數組自身,用來把某些個位置的元素複製並覆蓋到其他位置上去。以下重點介紹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]

以上是ES6中Array.copyWithin()函數用法的詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn