前言
Array.copyWithin是ES6新增的一个方法
使用
arr.copyWithin(target[, start[, end]])
target (必填)
即将被复制内容替换的开始位置,必须为整数,允许负数。如果 target 大于等于 arr.length,将会不发生拷贝。
start(可选)
默认值为0,开始复制元素的起始位置。允许负数,start 将从末尾开始计算。
end(可选)
默认值为arr.length,开始复制元素的结束位置。允许负数,start 将从末尾开始计算。不包括 end 这个位置的元素。
console.log([1,2,3,4,5].copyWithin(0, 1,5))
// 输出:[2, 3, 4, 5, 5]
其中target为0(即1),start为1(即2),end为arr.length(即5),通过start和end,我们拿到2, 3, 4, 5这些值,然后我们将从tartget位置开始替换。
target索引为负数
console.log([1,2,3,4,5].copyWithin(-1)) // target索引为-1(即5)
//输出:[1, 2, 3, 4, 1]
其中target为-1(即5),start为0(即1),end为arr.length(即5),通过start和end,我们拿到1, 2, 3, 4这些值,然后我们将从tartget位置开始替换。
console.log([1,2,3,4,5].copyWithin(0,-1))
//输出:[5, 2, 3, 4, 5]
其中target为0(即1),start为-1(即5),end为arr.length(即5),通过start和end,我们拿到5这个值,然后我们将从tartget位置开始替换。
总结
希望各位能给各位提供一些帮助和自己的记录。