ArrayBuffer.prototype.resize()

ArrayBuffer 实例的 resize() 方法将 ArrayBuffer 的大小调整为指定大小(以字节为单位)。

¥The resize() method of ArrayBuffer instances resizes the ArrayBuffer to the specified size, in bytes.

Try it

语法

¥Syntax

js
resize(newLength)

参数

¥Parameters

newLength

ArrayBuffer 大小调整为的新长度(以字节为单位)。

返回值

¥Return value

无 (undefined)。

¥None (undefined).

例外情况

¥Exceptions

TypeError

如果 ArrayBuffer 已分离或无法调整大小,则会抛出该异常。

RangeError

如果 newLength 大于 ArrayBuffermaxByteLength,则抛出。

描述

¥Description

resize() 方法将 ArrayBuffer 的大小调整为 newLength 参数指定的大小,前提是 ArrayBufferresizable,并且新大小小于或等于 ArrayBuffermaxByteLength。新字节被初始化为 0。

¥The resize() method resizes an ArrayBuffer to the size specified by the newLength parameter, provided that the ArrayBuffer is resizable and the new size is less than or equal to the maxByteLength of the ArrayBuffer. New bytes are initialized to 0.

请注意,你可以使用 resize() 来缩小或增大 ArrayBuffer — 允许 newLength 小于 ArrayBuffer 的当前 byteLength

¥Note that you can use resize() to shrink as well as grow an ArrayBuffer — it is permissible for newLength to be smaller than the ArrayBuffer's current byteLength.

示例

¥Examples

使用调整大小()

¥Using resize()

在此示例中,我们创建一个 8 字节缓冲区,最大长度可调整为 16 字节,然后检查其 resizable 属性,如果 resizable 返回 true 则调整其大小:

¥In this example, we create a 8-byte buffer that is resizable to a max length of 16 bytes, then check its resizable property, resizing it if resizable returns true:

js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });

if (buffer.resizable) {
  console.log("Buffer is resizable!");
  buffer.resize(12);
}

规范

Specification
ECMAScript Language Specification
# sec-arraybuffer.prototype.resize

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看