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

[].copyWithin.call({length: 5, 3: 1}, 0, 3); //结果:{0:1,3:1,length:5}

阅读 5.9k
4 个回答
({0:undefined,1:undefined,2:undefined,3: 1,4:undefined,5:undefined,length: 5}).copyWithin(0,3,5);
结果为:
{0:1,1:undefined,2:undefined,3: 1,4:undefined,5:undefined,length: 5};
也就是
{0:1,3:1,length:5}

首先:
需要了解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)){
    if(i in objectLikeArray){
      objectLikeArray[target]=objectLikeArray[i];
    }else{
      delete objectLikeArray[target]
    }
    target++;
}
return objectLikeArray;
}({length: 5, 3: 1},0,3));

copyWithin并不要求其作用的target是一个数组对象。

这个例子就是在对象{length: 5, 3: 1}上调用copyWithin,把索引是3的值拷贝到索引为0的地方。

{length: 5, 3: 1}定义了一个object,这个对象可以当做数组来用
看下面的例子

a={length: 5, 3: 1};
console.log(a.length);
console.log(a[0]);
console.log(a[3]);
[].copyWithin.call(a, 0, 3); 
console.log(a[0]);
console.log(a[3]);
// 首先去了解copyWithin()方法的基本使用。
// 对象{length: 5, 3: 1}有两个属性。
// length属性决定此对象为类数组对象,因此可使用copyWithin方法;
// 另外有一个key为3值为1的属性。
// 将3号位复制到0号位,因此导致创建key为0,值为1(与key为3的值一样)的属性。
// 返回{0: 1, 3: 1, length: 5}
[].copyWithin.call({length: 5, 3: 1}, 0, 3)

// 可类推返回{2: 1, 3: 1, length: 5}
[].copyWithin.call({length: 5, 3: 1}, 2, 3)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进