实现说明
各个操作都建立在顶层绑定之上:seq、ring、overlap、same。
使用要点
- 演示输出是带标签的(
length:),每个操作都会留下自己的一行标注。
常见问题
安装包是准备工作的一部分吗?
不需要。只用内建 API,安装这一步可以省掉。 跨调用保留的状态放在这些顶层绑定里:seq、ring、overlap。
核心语句
const same = [9, 8, 7].copyWithin(0, 1);
const ring = [10, 20, 30, 40, 50];
const overlap = [1, 2, 3, 4];
代码示例
// copyWithin(target, start, end):切片原地复制到 target,长度不变
const seq = [1, 2, 3, 4, 5];
seq.copyWithin(3, 1, 3);
console.log(seq);
// 负索引从尾部计数:target -2 表示倒数第二个位置
const ring = [10, 20, 30, 40, 50];
ring.copyWithin(-2, 0);
console.log(ring);
// 区间重叠安全:内部先整段读出再写回,等价 memmove 语义
const overlap = [1, 2, 3, 4];
overlap.copyWithin(1, 0, 3);
console.log(overlap);
// 返回同一个数组引用,不产生新对象
const same = [9, 8, 7].copyWithin(0, 1);
console.log('length:', same.length, '| same array:', same);