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

浏览器兼容性

另见