copyWithin()可以复制数组的一部分到该数组的其它位置,该方法会改变数组的内容,但是不会改变数组的长度。
语法:copyWithin(target,start,end),所有参数必须为整数
参数target
1.当只有target参数时,会将从0索引开始复制,然后从当前位置粘贴序列
let arr1 = [1,2,3,4,5,6,7,8,9,10];
arr1.copyWithin(3);
console.log(arr1);
// 输出[1, 2, 3, 1, 2, 3, 4, 5, 6, 7]
2.当复制的序列在粘贴时超出了数组的长度,将会自动裁剪
let arr1 = [1,2,3,4,5,6,7,8,9,10];
arr1.copyWithin(20);
console.log(arr1);
// 输出[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3.当target参数是一个负数的时候,会以target的绝对值为索引复制之前的序列,然后从末尾粘贴
let arr1 = [1,2,3,4,5,6,7,8,9,10];
arr1.copyWithin(-3);
console.log(arr1);
// 输出[1, 2, 3, 4, 5, 6, 7, 1, 2, 3]
参数start和参数end
start参数表示要复制元素的起点,以0为索引基点,如果没有start参数,copyWithin将会默认从0开始复制。
end参数表示要复制元素的终点,以0为索引基点,且当前如果没有end参数,copyWithin将会一直复制到数组的末尾。
let arr1 = [1,2,3,4,5,6,7,8,9,10];
arr1.copyWithin(3,4,7);
console.log(arr1);
// 输出[1, 2, 3, 5, 6, 7, 7, 8, 9, 10]
1.start和end参数为负值时,从末尾开始计算
let arr1 = [1,2,3,4,5,6,7,8,9,10];
arr1.copyWithin(3,-3,8);
console.log(arr1);
// 输出[1, 2, 3, 8, 5, 6, 7, 8, 9, 10]
let arr1 = [1,2,3,4,5,6,7,8,9,10];
arr1.copyWithin(3,2,-5);
console.log(arr1);
// 输出[1, 2, 3, 3, 4, 5, 7, 8, 9, 10]
let arr1 = [1,2,3,4,5,6,7,8,9,10];
arr1.copyWithin(1,-6,-4);
console.log(arr1);
// 输出[1, 5, 6, 4, 5, 6, 7, 8, 9, 10]
2.start参数在数组中的位置一定要小于end参数在数组中的位置,否则数组不会发生变化
let arr1 = [1,2,3,4,5,6,7,8,9,10];
arr1.copyWithin(3,8,7);
console.log(arr1);
// 输出[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3.当target大于start时,不会影响复制序列
let arr1 = [1,2,3,4,5,6,7,8,9,10];
arr1.copyWithin(3,1,4);
console.log(arr1);
// 输出[1, 2, 3, 2, 3, 4, 7, 8, 9, 10]
上述为个人理解,如有错误,请指正。