ES6 中运行[].copyWithin.call({length: 5, 3: 1}, 0, 3);

copyWithin方法的功能

arr.copyWithin(target, start[, end = this.length])

将start到end之间指定的子元素复制到arr中target指定的开始位置,并返回arr,

var p=[1,2,3,4,5];
p.copyWithin(0,3); //[4,5,3,4,5]
console.log(p);//[4,5,3,4,5]

[1,2,3,4,5].copyWithin(1,3);
//[1,4,5,4,5]

[1,2,,4,5].copyWithin(0,1);
//[2, 2: 4, 3: 5, 4: 5]

copyWith方法指出

The copyWithin function is intentionally generic, it does not require that its this value be an Array object and in addition, copyWithin is a mutable method, it will change this object itself, and return it, not just return a copy of it.
copytWithin方法并不要求this对象值是一个Array对象,类数组对象也是可以的,它会修改自己,然后返回,而不是返回一个copy值
[].copyWithin.call({length: 5, 3: 1}, 0, 3); //{0:1,3:1,length:5}

[].copyWithin获取copyWithin函数对象
call为任何一个函数对象都有的方法
call方法的第1个参数为call方法运行的上下文,也就是我们经常遇到的函数调用时候的this

{length: 5, 3: 1}这个对象具有一个length属性,那么其就是一个类数组对象(鸭子模式),并且这个对象具有一个属性key为3的值。这个对象等价于一个”数组对象”
那么copyWithin方法在执行的时候读取类数组对象下标3到末尾的元素,赋值到指定位置.执行简化后的copyWithin代码如下

(function(objectLikeArray, targetIn,startIndex){
var target= targetIn;
for(var i= startIndex;i<objectLikeArray.length;i++){
    if(objectLikeArray.hasOwnProperty(i)){
      objectLikeArray[target]=objectLikeArray[i];
    }else{
      delete objectLikeArray[target]
    }
    target++;
}
return objectLikeArray;
}({length: 5, 3: 1},0,3));

练习一下:

[].copyWithin.call({length: 5, 4: 1}, 0, 4);
//{"0":1,"4":1,"length":5}
[].copyWithin.call({length: 5, 3: 1}, 0, 2);
// {"1":1,"3":1,"length":5}
[].copyWithin.call({length: 8, 6: 10}, 1, 3)
//{"4":10,"6":10,"length":8}

原文链接:https://segmentfault.com/q/1010000004571952/a-1020000004572784/revision

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值