Get to know MDN better
此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年9月.
Array 實體的 copyWithin() 方法會將陣列中的部分元素進行淺複製,並將其放置於陣列內的另一個位置,同時返回該陣列,但不改變其長度。
要複製序列至的以零為基底的索引,會轉換為整數。這對應到 start 位置的元素將被複製至 target,而 start 和 end 之間的所有元素會依序複製至後續索引。
要開始複製元素的以零為基底的索引,會轉換為整數。
要結束複製元素的以零為基底的索引,會轉換為整數。copyWithin() 會複製至 end 之前的元素,但不包含 end。
被修改的陣列。
copyWithin() 方法類似於 C 和 C++ 的 memmove,它是一種高效能的方法,可用來移動 Array 的資料。這在 TypedArray 方法中尤其適用。該方法會將選定的序列一次性複製並貼上,即使複製區域與貼上區域重疊,貼上的序列仍然會保留已複製的值。
由於 undefined 轉換為整數時會變為 0,因此省略 start 參數的效果與傳入 0 相同,這會導致整個陣列被複製到目標位置,相當於向右位移,並裁剪右邊界、重複左邊界。此行為可能會讓你的程式碼讀者感到困惑,因此建議顯式傳入 0 作為 start。
copyWithin() 方法是一個可變異方法。它不會改變 this 的長度,但會改變 this 的內容,並在必要時新增或刪除屬性。
copyWithin() 方法會保留空槽。如果被複製的區域是稀疏陣列,則空槽對應的新索引會被刪除,並仍然為空槽。
copyWithin() 方法是通用的。它只要求 this 具有 length 屬性及整數鍵屬性。雖然字串也類似陣列,但此方法不適用於字串,因為字串是不可變的。
copyWithin() 會傳播空槽。
copyWithin() 方法會讀取 this 的 length 屬性,並操作其中的整數索引。
| ECMAScript® 2027 Language Specification # sec-array.prototype.copywithin |
Enable JavaScript to view this browser compatibility table.
This page was last modified on 2025年7月14日 by MDN contributors.
Your blueprint for a better internet.
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.