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.
Code
// 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,7How 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
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Timezone Offset FinderLook up the UTC offset, abbreviation, and local time for any IANA time zone at a given instant, and see whether the zone observes daylight saving.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.