DataView.prototype.byteLength

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

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

瀏覽器相容性

另見