ArrayBuffer() 构造函数

ArrayBuffer() 构造函数创建 ArrayBuffer 对象。

¥The ArrayBuffer() constructor creates ArrayBuffer objects.

Try it

语法

¥Syntax

js
new ArrayBuffer(length)
new ArrayBuffer(length, options)

注意:ArrayBuffer() 只能与 new 一起构建。尝试在没有 new 的情况下调用它会抛出 TypeError

¥Note: ArrayBuffer() can only be constructed with new. Attempting to call it without new throws a TypeError.

参数

¥Parameters

length

要创建的数组缓冲区的大小(以字节为单位)。

options Optional

一个对象,可以包含以下属性:

maxByteLength Optional

数组缓冲区大小可调整到的最大大小(以字节为单位)。

返回值

¥Return value

指定大小的新 ArrayBuffer 对象,其 maxByteLength 属性设置为指定的 maxByteLength(如果已指定)。其内容初始化为 0。

¥A new ArrayBuffer object of the specified size, with its maxByteLength property set to the specified maxByteLength if one was specified. Its contents are initialized to 0.

例外情况

¥Exceptions

RangeError

有下列情况之一的,抛出:

示例

¥Examples

创建一个 ArrayBuffer

¥Creating an ArrayBuffer

在此示例中,我们创建一个 8 字节缓冲区,并使用引用该缓冲区的 Int32Array 视图:

¥In this example, we create a 8-byte buffer with a Int32Array view referring to the buffer:

js
const buffer = new ArrayBuffer(8);
const view = new Int32Array(buffer);

创建一个可调整大小的 ArrayBuffer

¥Creating a resizable ArrayBuffer

在此示例中,我们创建一个 8 字节缓冲区,最大长度可调整为 16 字节,然后将其 resize() 为 12 字节:

¥In this example, we create a 8-byte buffer that is resizable to a max length of 16 bytes, then resize() it to 12 bytes:

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

buffer.resize(12);

注意:建议将 maxByteLength 设置为适合你的用例的最小值。它不应超过 1073741824 (1GB),以降低内存不足错误的风险。

¥Note: It is recommended that maxByteLength is set to the smallest value possible for your use case. It should never exceed 1073741824 (1GB) to reduce the risk of out-of-memory errors.

规范

Specification
ECMAScript Language Specification
# sec-arraybuffer-constructor

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看