实现说明
各个操作都建立在顶层绑定之上:buffer、bytes、words、cells。
使用要点
- 演示输出是带标签的(
byte[0] :、word[0] :),每个操作都会留下自己的一行标注。
常见问题
运行前要先安装什么?
什么都不用额外装——运行时自带了代码所需的一切。 跨调用保留的状态放在这些顶层绑定里:buffer、bytes、words。
核心语句
const lowBytes = new Uint8Array(buffer, 0, 4);
const words = new Uint16Array(buffer);
const bytes = new Uint8Array(buffer);
代码示例
// 同一块内存的三种视图:字节、16 位、32 位
const buffer = new ArrayBuffer(16);
const bytes = new Uint8Array(buffer);
const words = new Uint16Array(buffer);
const cells = new Int32Array(buffer);
cells[0] = 0x12345678;
console.log('byte[0] :', bytes[0].toString(16));
console.log('word[0] :', words[0].toString(16));
console.log('endian :', bytes[0] === 0x78 ? 'little' : 'big');
// 切片视图共享内存,不复制数据
const lowBytes = new Uint8Array(buffer, 0, 4);
lowBytes[0] = 0xff;
console.log('alias :', bytes[0] === 0xff && cells[0] !== 0x12345678);
// slice 复制:新 buffer 互不影响
const copy = buffer.slice(0, 4);
new Uint8Array(copy)[0] = 0x00;
console.log('copy :', bytes[0] === 0xff);
// transfer 分离:所有权移交给新 buffer,旧的所有视图全部失效
const moved = buffer.transfer();
console.log('moved :', moved.byteLength);
try {
bytes[0];
} catch (err) {
console.log('detached:', err.name);
}