Array.prototype.copyWithin()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 2015 年 9 月以來,該特性已在各大瀏覽器中可用。

copyWithin() 方法用於淺複製陣列的一部分到同一陣列的另一個位置,並返回該陣列,但不會修改其長度。

試一試

const array = ["a", "b", "c", "d", "e"];

// Copy to index 0 the element at index 3
console.log(array.copyWithin(0, 3, 4));
// Expected output: Array ["d", "b", "c", "d", "e"]

// Copy to index 1 all elements from index 3 to the end
console.log(array.copyWithin(1, 3));
// Expected output: Array ["d", "d", "e", "d", "e"]

語法

js
copyWithin(target, start)
copyWithin(target, start, end)

引數

目標

要將序列複製到的零基索引,已轉換為整數。這對應於 start 處的元素將被複制到的位置,而 startend 之間的所有元素將被複制到後續索引。

  • 負數索引從陣列末尾開始計數 — 如果 -array.length <= target < 0,則使用 target + array.length
  • 如果 target < -array.length,則使用 0
  • 如果 target >= array.length,則不復制任何內容。
  • 如果 target 在標準化後位於 start 之後,則複製僅進行到 array.length 的末尾(換句話說,copyWithin() 永遠不會擴充套件陣列)。
start

要開始複製元素的零基索引,已轉換為整數

  • 負數索引從陣列末尾開始計數——如果 -array.length <= start < 0,則使用 start + array.length
  • 如果 start < -array.length,則使用 0
  • 如果 start >= array.length,則不復制任何內容。
end 可選

要結束複製元素的零基索引,已轉換為整數copyWithin() 會複製到 end 之前,但不包括 end

  • 負數索引從陣列末尾開始計數——如果 -array.length <= end < 0,則使用 end + array.length
  • 如果 end < -array.length,則使用 0
  • 如果 end >= array.lengthend 被省略或為 undefined,則使用 array.length,這將複製所有元素直到末尾。
  • 如果 end 暗示的位置在 start 暗示的位置之前或與之相同,則不復制任何內容。

返回值

修改後的陣列。

描述

copyWithin() 方法類似於 C 和 C++ 的 memmove,是一種高效能的移位 Array 資料的方法。這尤其適用於同名的 TypedArray 方法。序列作為一個操作被複制和貼上;即使複製和貼上區域重疊,貼上的序列也會具有複製的值。

由於 undefined 在轉換為整數時變為 0,因此省略 start 引數的效果與傳入 0 相同,即將整個陣列複製到目標位置,相當於一個右移,其中右邊界被截斷,左邊界被重複。這種行為可能會讓程式碼閱讀者感到困惑,因此你應該顯式地傳入 0 作為 start

js
console.log([1, 2, 3, 4, 5].copyWithin(2));
// [1, 2, 1, 2, 3]; move all elements to the right by 2 positions

copyWithin() 方法是修改方法。它不會改變 this 的長度,但如果需要,它會更改 this 的內容並建立新屬性或刪除現有屬性。

copyWithin() 方法會保留空槽。如果要複製的區域是稀疏的,那麼空槽對應的新的索引會被刪除,並且也變成空槽。

copyWithin() 方法是通用的。它只期望 this 值具有 length 屬性和整數鍵屬性。雖然字串也像陣列一樣,但該方法不適合應用於字串,因為字串是不可變的。

示例

使用 copyWithin()

js
console.log([1, 2, 3, 4, 5].copyWithin(0, 3));
// [4, 5, 3, 4, 5]

console.log([1, 2, 3, 4, 5].copyWithin(0, 3, 4));
// [4, 2, 3, 4, 5]

console.log([1, 2, 3, 4, 5].copyWithin(-2, -3, -1));
// [1, 2, 3, 3, 4]

在稀疏陣列上使用 copyWithin()

copyWithin() 會傳播空槽。

js
console.log([1, , 3].copyWithin(2, 1, 2)); // [1, empty, empty]

在非陣列物件上呼叫 copyWithin()

copyWithin() 方法讀取 thislength 屬性,然後操作涉及的整數索引。

js
const arrayLike = {
  length: 5,
  3: 1,
};
console.log(Array.prototype.copyWithin.call(arrayLike, 0, 3));
// { '0': 1, '3': 1, length: 5 }
console.log(Array.prototype.copyWithin.call(arrayLike, 3, 1));
// { '0': 1, length: 5 }
// The '3' property is deleted because the copied source is an empty slot

規範

規範
ECMAScript® 2026 語言規範
# sec-array.prototype.copywithin

瀏覽器相容性

另見