ArrayBuffer.prototype.resize()
ArrayBuffer 例項的 resize() 方法會將 ArrayBuffer 的大小調整為指定的位元組數。
試一試
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
console.log(buffer.byteLength);
// Expected output: 8
buffer.resize(12);
console.log(buffer.byteLength);
// Expected output: 12
語法
js
resize(newLength)
引數
newLength-
將
ArrayBuffer調整到的新長度(以位元組為單位)。
返回值
無(undefined)。
異常
TypeError-
如果
ArrayBuffer已分離或不可調整大小,則丟擲此錯誤。 RangeError-
如果
newLength大於ArrayBuffer的maxByteLength,則丟擲此錯誤。
描述
resize() 方法會將 ArrayBuffer 的大小調整為 newLength 引數指定的大小,前提是該 ArrayBuffer 是 可調整大小的,並且新大小小於或等於 ArrayBuffer 的 maxByteLength。新增的位元組將初始化為 0。
請注意,您可以使用 resize() 來縮小或增大 ArrayBuffer — 允許 newLength 小於 ArrayBuffer 當前的 byteLength。
示例
使用 resize()
在此示例中,我們建立一個 8 位元組的可調整大小的緩衝區,其最大長度為 16 位元組,然後檢查其 resizable 屬性,如果 resizable 返回 true,則調整其大小。
js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
if (buffer.resizable) {
console.log("Buffer is resizable!");
buffer.resize(12);
}
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-arraybuffer.prototype.resize |
瀏覽器相容性
載入中…