copyWithin Moves Values Inside The Array

copyWithin moves a slice inside the same array without changing its length, reading before writing so overlapping ranges behave like memmove.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
// 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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How the snippet works

The file’s state is a handful of top-level bindings: seq, ring, overlap, same.

Using it

The demo output is labeled (length:), so every printed line maps back to its originating operation.

Key statements

const same = [9, 8, 7].copyWithin(0, 1);
const ring = [10, 20, 30, 40, 50];
const overlap = [1, 2, 3, 4];

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. Its state lives in module-level bindings: `seq`, `ring`, `overlap`.