ArrayBuffer.prototype.transferToFixedLength()

ArrayBuffer 实例的 transferToFixedLength() 方法创建一个新的不可调整大小的 ArrayBuffer,其字节内容与此缓冲区相同,然后分离此缓冲区。

¥The transferToFixedLength() method of ArrayBuffer instances creates a new non-resizable ArrayBuffer with the same byte content as this buffer, then detaches this buffer.

语法

¥Syntax

js
transferToFixedLength()
transferToFixedLength(newByteLength)

参数

¥Parameters

newByteLength

新款 ArrayBufferbyteLength。默认为该 ArrayBufferbyteLength

  • 如果 newByteLength 小于这个 ArrayBufferbyteLength,则 "overflowing" 字节被丢弃。
  • 如果 newByteLength 大于该 ArrayBufferbyteLength,则多余的字节用零填充。

返回值

¥Return value

一个新的 ArrayBuffer 对象。其内容被初始化为该 ArrayBuffer 的内容,并且额外的字节(如果有)用零填充。新的 ArrayBuffer 始终不可调整大小。原来的 ArrayBuffer 已分离。

¥A new ArrayBuffer object. Its contents are initialized to the contents of this ArrayBuffer, and extra bytes, if any, are filled with zeros. The new ArrayBuffer is always non-resizable. The original ArrayBuffer is detached.

例外情况

¥Exceptions

TypeError

如果此 ArrayBuffer 已分离,则抛出此异常。

描述

¥Description

transfer() 不同,transferToFixedLength() 始终创建不可调整大小的 ArrayBuffer。这意味着 newByteLength 可以大于 maxByteLength,即使 ArrayBuffer 的大小是可调整的。请参阅 传输 ArrayBuffer 了解更多信息。

¥Unlike transfer(), transferToFixedLength() always creates a non-resizable ArrayBuffer. This means newByteLength can be larger than the maxByteLength, even if this ArrayBuffer is resizable. See transferring ArrayBuffers for more information.

示例

¥Examples

将可调整大小的 ArrayBuffer 转换为固定长度

¥Transferring a resizable ArrayBuffer to fixed-length

js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const view = new Uint8Array(buffer);
view[1] = 2;
view[7] = 4;

const buffer2 = buffer.transferToFixedLength();
console.log(buffer2.byteLength); // 8
console.log(buffer2.resizable); // false
const view2 = new Uint8Array(buffer2);
console.log(view2[1]); // 2
console.log(view2[7]); // 4

使用 transferToFixedLengthnewByteLength 可以比原来的 ArrayBuffermaxByteLength 大。

¥Using transferToFixedLength, newByteLength can be larger than the maxByteLength of the original ArrayBuffer.

js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const view = new Uint8Array(buffer);
view[1] = 2;
view[7] = 4;

const buffer2 = buffer.transferToFixedLength(20);
console.log(buffer2.byteLength); // 20
console.log(buffer2.resizable); // false
const view2 = new Uint8Array(buffer2);
console.log(view2[1]); // 2
console.log(view2[7]); // 4

规范

Specification
ArrayBuffer transfer
# sec-arraybuffer.prototype.transfertofixedlength

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看