若要將 ArrayBuffer
的內容擷取為數字陣列,請在緩衝區上建立一個 Uint8Array
,並使用 Array.from()
方法將其轉換為陣列。
const buf = new ArrayBuffer(64);
const arr = new Uint8Array(buf);
arr.length; // 64
arr[0]; // 0 (instantiated with all zeros)
Uint8Array
類別支援陣列索引和反覆運算。但是,如果你希望將實例轉換為常規 Array
,請使用 Array.from()
。(這可能會比直接使用 Uint8Array
慢。)
const buf = new ArrayBuffer(64);
const uintArr = new Uint8Array(buf);
const regularArr = Array.from(uintArr);
// number[]
請參閱 文件 > API > 二進制資料,以取得使用 Bun 操作二進制資料的完整文件。