js数组操作方法copyWithin

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]

上述为个人理解,如有错误,请指正。

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值