ArrayBuffer Views Alias Until Transfer
Overlay typed-array views on one ArrayBuffer: aliased writes, endian byte order, copied slices, and detached buffers after transfer().
Code
// 同一块内存的三种视图:字节、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);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
byte[0] : 78
word[0] : 5678
endian : little
alias : true
copy : true
moved : 16Inside the snippet
Module-level bindings hold the data — buffer, bytes, words, cells — with no function scope in between.
Putting it to use
Running the file prints labeled results such as byte[0] :, word[0] :, endian : — each operation’s effect is visible in the output.
Core lines
const lowBytes = new Uint8Array(buffer, 0, 4);
const words = new Uint16Array(buffer);
const bytes = new Uint8Array(buffer);
Interactive Tools for This Topic
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. Its state lives in module-level bindings: `buffer`, `bytes`, `words`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.