copyWithin
Array.prototype.copyWithin 不改变数组长度
target start end
前闭后开
从start到end复制到target位置上
流程
复制 -> 全选target及符合复制的元素集合的长度的元素 -> 粘贴
end > len - 1
取到末尾
const arr = [1, 2, 3, 4, 5];
const newArr = arr.copyWithin(0, 2,6);
console.log(newArr);//[ 3, 4, 5, 4, 5 ]
target > len - 1
不发生任何替换
const arr = [1, 2, 3, 4, 5];
const newArr = arr.copyWithin(7, 2, 3);
console.log(newArr);//[1,2,3,4,5]
target > start
正常替换
const arr = [1, 2, 3, 4, 5];
const newArr = arr.copyWithin(3, 1, 3);//[ 1, 2, 3, 2, 3 ]
console.log(newArr);
start 或 end 是负数
start + length end + length
const arr = [1, 2, 3, 4, 5];
const newArr = arr.copyWithin(0, -3, -1);//[ 3, 4, 3, 4, 5 ]
console.log(newArr);
如果没有start
取整个数组的元素
const arr = [1, 2, 3, 4, 5];
const newArr = arr.copyWithin(3);//[ 1, 2, 3, 1, 2 ]
const newArr = arr.copyWithin(1, 3); //[ 1, 4, 5, 4, 5 ]
console.log(newArr);
返回的是原数组引用
const arr = [1, 2, 3, 4, 5];
const newArr = arr.copyWithin(0, -3, -1);
console.log(newArr === arr); //true
浅拷贝
const arr = [
{
id: 1,
name: '张三',
},
{
id: 2,
name: '李四',
},
{
id: 3,
name: '王五',
},
{
id: 4,
name: '赵六',
},
{
id: 5,
name: '刘七',
},
];
const target1 = arr[0];
const newArr = arr.copyWithin(0, 2, 3);
const target2 = arr[0];
console.log(target1 === target2); //false
console.log(newArr);
/*
[
{ id: 3, name: '王五' },
{ id: 2, name: '李四' },
{ id: 3, name: '王五' },
{ id: 4, name: '赵六' },
{ id: 5, name: '刘七' }
]
*/
const arr = [
{
id: 1,
name: '张三',
},
{
id: 2,
name: '李四',
},
{
id: 3,
name: '王五',
},
{
id: 4,
name: '赵六',
},
{
id: 5,
name: '刘七',
},
];
const target1 = arr[2];
const newArr = arr.copyWithin(0, 2, 3);
const target2 = arr[0];
console.log(target1 === target2); //true
this不一定非要指向一个数组 也可以指向一个对象
var obj = {
0: 1,
1: 2,
2: 3,
3: 4,
4: 5,
length: 5,
};
const newObj = [].copyWithin.call(obj, 0, 2, 4);
console.log(newObj); //{ '0': 3, '1': 4, '2': 3, '3': 4, '4': 5, length: 5 }
console.log(obj === newObj); // true
定义myCopyWithin
Array.prototype.myCopyWithin = function (target) {
if (this == null) {
throw new TypeError('this is null or nut defined');
}
var obj = Object(this),
len = obj.length >>> 0, //无符号右移保证是正整数
start = arguments[1],
end = arguments[2],
count = 0,
dir = 1;
target = target >> 0; //有符号右移0 保证是整数
target = target < 0 ? Math.max(len + target, 0) : Math.min(target, len);
start = start ? start >> 0 : 0;
start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
end = end ? end >> 0 : len;
end = end < 0 ? Math.max(len + end, 0) : Math.min(end, len);
count = Math.min(end - start, len - target);
if (start < target && target < start + count) {
dir = -1;
start += count - 1;
target += count - 1;
}
while (count > 0) {
if (target in obj) {
obj[target] = obj[start];
} else {
delete obj[start];
}
start += dir;
target += dir;
count--;
}
return obj;
};