ArrayBuffer() 构造函数
ArrayBuffer()
构造函数创建 ArrayBuffer
对象。
¥The ArrayBuffer()
constructor creates ArrayBuffer
objects.
Try it
语法
参数
¥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
-
有下列情况之一的,抛出:
length
或maxByteLength
大于Number.MAX_SAFE_INTEGER
(≥ 253) 或负数。length
大于maxByteLength
。
示例
创建一个 ArrayBuffer
¥Creating an ArrayBuffer
在此示例中,我们创建一个 8 字节缓冲区,并使用引用该缓冲区的 Int32Array
视图:
¥In this example, we create a 8-byte buffer with a Int32Array
view referring to the buffer:
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:
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 exceed1073741824
(1GB) to reduce the risk of out-of-memory errors.
规范
Specification |
---|
ECMAScript Language Specification # sec-arraybuffer-constructor |
浏览器兼容性
BCD tables only load in the browser