DataView.prototype.byteLength
byteLength 访问器属性,属于 DataView 实例,返回该视图的长度(以字节为单位)。
试一试
// Create an ArrayBuffer with a size in bytes
const buffer = new ArrayBuffer(16);
const view1 = new DataView(buffer);
const view2 = new DataView(buffer, 12, 4); // From byte 12 for the next 4 bytes
console.log(view1.byteLength + view2.byteLength); // 16 + 4
// Expected output: 20
描述
byteLength 属性是一个访问器属性,其 set 访问器函数为 undefined,这意味着你只能读取此属性。如果 DataView 是 长度跟踪的,则其长度取决于底层缓冲区的长度,并且在缓冲区被调整大小时可能会发生变化。否则,该值在构造 DataView 时确定,并且无法更改。无论是否进行长度跟踪,如果底层缓冲区被调整到使其查看的范围不再有效,byteLength 将变为 0。
示例
使用 byteLength 属性
js
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.byteLength; // 8 (matches the byteLength of the buffer)
const dataview2 = new DataView(buffer, 1, 5);
dataview2.byteLength; // 5 (as specified when constructing the DataView)
const dataview3 = new DataView(buffer, 2);
dataview3.byteLength; // 6 (due to the offset of the constructed DataView)
const buffer2 = new ArrayBuffer(16, { maxByteLength: 32 });
const dataviewLengthTracking = new DataView(buffer2, 4);
dataviewLengthTracking.byteLength; // 12 (16 - 4)
buffer2.resize(20);
dataviewLengthTracking.byteLength; // 16 (20 - 4)
buffer2.resize(3);
dataviewLengthTracking.byteLength; // 0 (viewed range is no longer valid)
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-get-dataview.prototype.bytelength |
浏览器兼容性
加载中…