copyWithin()
方法将数组中的元素从一个位置复制到给定 数组 中的另一个位置。
示例
let words = ["apple", "ball", "cat", "dog"];
// copies element from index 0 to index 3
words.copyWithin(3, 0);
// modifies the original array
console.log(words);
// Output:
// [ ''apple'', ''ball'', ''cat'', ''apple'' ]
copyWithin() 语法
copyWithin()
方法的语法是
arr.copyWithin(target, start, end)
这里,arr 是一个数组。
copyWithin() 参数
copyWithin()
方法可以接受 **三个** 参数
- target - 要将元素复制到的索引位置。
- start (可选) - 要从中开始复制元素的索引位置。如果省略,则从索引 **0** 开始复制。
- end (可选) - 要从中停止复制元素的索引位置(不包含结束元素)。如果省略,则复制到最后一个索引。
注意事项
- 如果任何参数为负数,则索引将从后往前计算。例如,**-1** 表示最后一个元素,依此类推。
copyWithin()返回值
- 返回复制元素后修改后的数组。
注意: copyWithin()
方法
- 会覆盖原始数组。
- 不会改变原始数组的长度。
示例 1:使用 copyWithin() 方法
let numbers = [1, 2, 3, 4, 5];
// copying element located at 4th index to 0th index
numbers.copyWithin(0, 4);
// modifies the original array
console.log(numbers); // [ 5, 6, 3, 4, 5 ]
let letters = ["a", "b", "c", "d"];
// copying element located at 1st index to 2nd index
letters.copyWithin(2, 1);
// modifies the original array
console.log(letters); // [ 'a', 'b', 'b', 'c' ]
输出
[ 5, 2, 3, 4, 5 ] [ 'a', 'b', 'b', 'c' ]
在上面的示例中,我们使用 copyWithin()
方法在数组 numbers 和 letters 中将元素从一个索引复制到另一个索引。
numbers.copyWithin(0, 4)
将位于 start(即索引 4)的元素复制到 target(即索引 0),而 letters.copyWithin(2, 1)
将索引 **1** 的元素复制到索引 **2**。
示例 2:copyWithin() 使用三个参数
let laptops = ["dell", "hp", "acer", "asus"];
// copying elements from index 2 to 4(excluding 4) to index 0
laptops.copyWithin(0, 2, 4);
// modifies the original array
console.log(laptops); // [ 'acer', 'asus', 'acer', 'asus' ]
输出
[ 'acer', 'asus', 'acer', 'asus' ]
在上面的示例中,我们在 copyWithin
方法中传递了三个参数:target、start 和 end。
laptops.copyWithin(0, 2, 4)
将索引 **2** 到 **4**(不包括索引 4)的元素复制到索引 **0**,并将 laptops 数组修改为 [ 'acer', 'asus', 'acer', 'asus' ]
。
示例 3:copyWithin() 使用负数参数
let evenNumbers= [2,4,6,8];
// passing negative index value -1 as target index
evenNumbers.copyWithin(-1);
console.log(evenNumbers);
输出
[ 2, 4, 6, 2 ]
在这里,我们在 copyWithin()
方法中将负索引值 **-1** 作为 target 的值传递。
由于传递的参数是负数,该方法将从后往前计算索引,因此 target 索引是最后一个索引。
evenNumbers.copyWithin(-1)
将索引 **0**(默认 start 值)的元素复制到最后一个索引。