TypedArray.set Copies Into Offset Views

TypedArray.set copies source data into an optional offset, converts across element widths with wrapping, and never shares memory with the source.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
// TypedArray.set 把源数组拷进视图:可指定目标偏移,按元素宽度落位
const target = new Uint8Array(8);
target.set([1, 2, 3]);
target.set([9, 9], 6);
console.log('target:', target.join(','));

// 跨类型拷贝走数值转换:300 写入 Uint8 会按模 256 回绕
const wide = new Uint16Array([300, 258]);
const narrow = new Uint8Array(2);
narrow.set(wide);
console.log('wrapped:', narrow.join(','));

// set 拷贝值而不共享内存:改源不影响目标
const source = new Uint8Array([5, 6, 7]);
const copy = new Uint8Array(3);
copy.set(source);
source[0] = 55;
console.log('copy detached:', copy.join(','));

Output

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

target: 1,2,3,0,0,0,9,9
wrapped: 44,2
copy detached: 5,6,7

How the snippet works

Top-level bindings target, wide, narrow, source hold the demo state — nothing sits inside a function scope.

Points of care

  • Runs on the standard library alone; nothing to install.

Applying it

The run emits 3 labeled sections — target:, wrapped:, copy detached: — one per step.

Statements that do the work

const wide = new Uint16Array([300, 258]);
const source = new Uint8Array([5, 6, 7]);
const target = new Uint8Array(8);

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Its state lives in module-level bindings: `target`, `wide`, `narrow`.