Array.prototype.copyWithin 数组

Array.prototype.copyWithin方法用于在原数组中复制一部分内容到指定位置。该方法接受index、start和end作为参数,可以正向或反向复制。文中通过多个示例展示了如何使用此方法以及其负数索引的处理方式,并提供了方法的实现代码。
摘要由CSDN通过智能技术生成

概念


Array.prototype.copyWithin方法复制数组的一部分到当前数组的另一个位置,并返回修改后的数组。

语法


arr.copyWithin(index)
arr.copyWithin(index, start)
arr.copyWithin(index, start, end)

参数

  • index 参照索引位置。

  • start 替换的起始位置,默认是0。

  • end 替换的结束位置,默认是数组长度。

返回值

返回修改后的数组。

描述


当索引是自然数时,从数组的起始位置向末尾位置依次访问。 当索引是负数时,从数组的末尾位置向起始位置依次访问。

例子


例一、

let arr = ['前', '端', '咖', '手', '册'];
let result = arr.copyWithin(1);
console.log(arr); // ['前', '前', '端', '手', '册'];
console.log(arr === result); // true
// 等价于
arr.copyWithin(1, 0, arr.length);

0

1

2

3

4

例二、

let arr = ['前', '端', '咖', '手', '册'];
let result = arr.copyWithin(1, 2);
console.log(arr); // ['前', '咖', '手', '册', '册']
console.log(arr === result); // true
// 等价于 
arr.copyWithin(1, 2, arr.length);

0

1

2

3

4

例三、

let arr = ['前', '端', '咖', '手', '册'];
let result = arr.copyWithin(1, 2, 3);
console.log(arr); // ['前', '咖', '咖', '手', '册']
console.log(arr === result); // true

0

1

2

3

4

例四、

let arr = ['前', '端', '咖', '手', '册'];
let result = arr.copyWithin(-3);
console.log(result); // ['前', '端', '前', '端', '咖']
// 等价于
console.log(arr.copyWithin(2, 0, arr.length)); // ['前', '端', '前', '端', '咖']

例五、

let arr = ['前', '端', '咖', '手', '册'];
let result = arr.copyWithin(-3, -1); 
console.log(result); // ['前', '端', '册', '手', '册']
// 等价于
console.log(arr.copyWithin(2, 4, arr.length)); // ['前', '端', '册', '手', '册']

实现 copyWithin 方法


if(!Array.prototype.copyWithin){
  Array.prototype.copyWithin = function (index, start, end) {
    if (index === undefined) {
      index = 0;
    }
    if (index < 0) {
      index = index + this.length;
    }
    index = Math.floor(index);
    if (start === undefined) {
      start = 0;
    }
    if (start < 0) {
      start = start + this.length;
    }
    start = Math.floor(start);
    if (end === undefined) {
      end = this.length;
    }
    if (end < 0) {
      end = end + this.length;
    }
    end = Math.floor(end);

    let copyArr = [];
    for (let i = 0; i < this.length; i++) {
      copyArr.push(this[i]);
    }

    let count = 0;
    for (let i = 0; i < this.length; i++) {
      if (index <= i && start + count < end) {
        this[i] = copyArr[start + count];
        count++;
      }
    }
    
    retun this;
  };
}

前端咖小程序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值