← 中文资源

简体中文版本

TypedArray.set 按偏移拷贝进视图

TypedArray.set 按偏移把源数组拷进目标视图,跨元素宽度走模 256 回绕转换;拷的是值不是内存,改源不动目标,适合手工拼装二进制包。

阅读英文原文

运行结果

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

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

实现说明

顶层就这几处状态:target、wide、narrow、source。

使用要点

  • 直接运行文件,输出会带上标签,比如 target:、wrapped:、copy detached:——输出的每一行都能指回产生它的那次调用。

常见问题

除了语言工具链还要下载什么吗?

除了这个语言的工具链,什么都不用再下载。 文件用顶层绑定保存自己的状态:target、wide、narrow。

核心语句

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

代码示例

// 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(','));