ES6為Array增加了copyWithin函數(shù),用于操作當(dāng)前數(shù)組自身,用來把某些個位置的元素復(fù)制并覆蓋到其他位置上去。
Array.prototype.copyWithin(target, start = 0, end = this.length)
該函數(shù)有三個參數(shù)。
target:目的起始位置。
start:復(fù)制源的起始位置,可以省略,可以是負(fù)數(shù)。
end:復(fù)制源的結(jié)束位置,可以省略,可以是負(fù)數(shù),實(shí)際結(jié)束位置是end-1。
例:
把第3個元素(從0開始)到第5個元素,復(fù)制并覆蓋到以第1個位置開始的地方。
下面的紅色塊是復(fù)制目標(biāo)的起始位置,黃色塊為復(fù)制的源。
const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] arr1.copyWithin(1, 3, 6) console.log('%s', JSON.stringify(arr1))
結(jié)果:
[1,4,5,6,5,6,7,8,9,10,11]
start和end都是可以省略。
start省略表示從0開始,end省略表示數(shù)組的長度值。
目標(biāo)的位置不夠的,能覆蓋多少就覆蓋多少。
const arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] arr2.copyWithin(3) console.log('%s', JSON.stringify(arr2))
結(jié)果:
[1,2,3,1,2,3,4,5,6,7,8]
start和end都可以是負(fù)數(shù),負(fù)數(shù)表示從右邊數(shù)過來第幾個。
const arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] arr3.copyWithin(3, -3, -2) console.log('%s', JSON.stringify(arr3))
結(jié)果:
[1,2,3,9,5,6,7,8,9,10,11]
總結(jié)
以上所述是小編給大家介紹的ES6中Array.copyWithin()函數(shù)的用法實(shí)例詳解,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com