← 中文资源

简体中文版本

copyWithin 在数组内部原地搬移切片

copyWithin 把数组的一段切片复制到目标位置:长度不变、返回原引用、负索引从尾部计数;重叠区间内部先读后写,语义等价 memmove,不会自我覆盖出脏数据。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

[ 1, 2, 3, 2, 3 ]
[ 10, 20, 30, 10, 20 ]
[ 1, 1, 2, 3 ]
length: 3 | same array: [ 8, 7, 7 ]

实现说明

各个操作都建立在顶层绑定之上: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);