WebGL Tutorial
and more

copyWithin

撰写时间:2024-03-05

最新修订:2024-03-09

copyWithin

在数组内复制。改变原数组。

原型

*[]copyWithin
  • numbertarget
  • numberstart
  • numberend

参数

target
目的索引值。
start
从该索引值的位置开始选取要复制的元素。
end
要复制的元素的结束位置的索引值。该位置的元素不在被复制的范围之内。

返回值

复制后的数组。是原来数组的引用。

说明

copyWithin方法在本数组内进行复制。它将该数组内多个连续的元素复制到target所指定的位置,将覆盖该位置之后的数组元素,而不是插入。

该方法属于在原地直接修改原来的数组内容,并返回原来数组的引用。

该方法不会改变数组的长度。

例子

复制时的内部细节

let arr = [5, 10, 15, 20, 25, 30, 35]; let res = arr.copyWithin(0, 4, 6); console.log(res); console.log(arr);

参数start的索引值为4,该索引值所在元素的值为25,参数end的值为6,不含在要复制的范围内。因此只有第4个到第5个索引位置的25, 30被选入要复制的范围。

第1个参数target指定了要复制到哪里的索引值。该值为0,表示将所选取的2个数组元素复制到第0个、第1个位置。这两个位置上原有的数据5, 10将被所选取的25, 30覆盖。因此复制后的数组res就变成了:

[25, 30, 15, 20, 25, 30, 35]

而原来的数组arr的内容为:

[25, 30, 15, 20, 25, 30, 35]

说明copyWithin方法将改变原来的数组内容。其返回的实例是原来数组的引用。

console.log(arr === res); // true

数组长度不会改变

let arr = [5, 10, 15, 20, 25, 30, 35]; let res = arr.copyWithin(5, 0, 6); console.log(res);

将第0个至第6个索引值的元素5, 10, 15, 20, 25序列,准备复制到第5个索引值(元素值为30)的位置。就是要将5个元素复制到只有2个元素的空间。结果为:

[5, 10, 15, 20, 25, 5, 10]

因空间有限,只有最前面的5, 10这两个元素得到了复制,其余的元素均被弃用了。也即说,copyWithin方法不会擅自改变原来数组的长度。

参数start及end可省略

当参数startend均省略时,默认选取全部的数组元素。

let arr = [5, 10, 15, 20, 25, 30, 35]; let res = arr.copyWithin(2); console.log(res); [5, 10, 5, 10, 15, 20, 25]

当只有参数end被省略时,将选取从参数start之后的全部元素。

let arr = [5, 10, 15, 20, 25, 30, 35]; let res = arr.copyWithin(2, 0); // [5, 10, 5, 10, 15, 20, 25]

参数start及end可为负数

当参数start为负数而end省略时,将选取从倒数第start个位置开始的所有剩余元素。

let arr = [5, 10, 15, 20, 25, 30, 35]; let res = arr.copyWithin(2, -2); console.log(res); // [5, 10, 30, 35, 25, 30, 35]

当参数startend均为负数,end的位置应在start位置的右边。否则,违背逻辑,则不会产生复制动作。

let arr = [5, 10, 15, 20, 25, 30, 35]; let res = arr.copyWithin(2, -2, -2); console.log(res); // [5, 10, 15, 20, 25, 30, 35] <- no copy // or let arr = [5, 10, 15, 20, 25, 30, 35]; let res = arr.copyWithin(2, -2, -3); console.log(res); // [5, 10, 15, 20, 25, 30, 35] <- no copy

参见

  1. fill
  2. splice

参考资源

  1. ECMA 262: Array Objects