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