Uint8Array
Baseline 廣泛可用 *
Uint8Array 型別化陣列表示一個 8 位無符號整數的陣列。除非明確提供了初始化資料,否則其內容將初始化為 0。一旦建立,您就可以使用該物件的方法或標準陣列索引語法(即方括號表示法)來引用陣列中的元素。
Uint8Array 是隱藏的 TypedArray 類的子類。
描述
Uint8Array 是目前唯一一個比其他型別化陣列擁有額外方法的 TypedArray 子類。由於它本身就是一個通用的位元組陣列,因此最適合處理任意二進位制資料。它支援兩套方法,用於將 Uint8Array 資料建立、序列化和修改為十六進位制字串和 base64 字串。
- 用於處理 base64 字串的
Uint8Array.fromBase64()、Uint8Array.prototype.toBase64()和Uint8Array.prototype.setFromBase64(),其中 3 個位元組被編碼為 4 個字元,這些字元可以是 0–9、A–Z、a–z、"+" 和 "/"(如果使用 URL 安全的 base64,則是 "-" 和 "_")。 - 用於處理十六進位制字串的
Uint8Array.fromHex()、Uint8Array.prototype.toHex()和Uint8Array.prototype.setFromHex(),其中每個位元組都由兩個字元編碼,每個字元可以是 0–9 或 A–F(不區分大小寫)。
建構函式
Uint8Array()-
建立一個新的
Uint8Array物件。
靜態屬性
也繼承了其父類 TypedArray 的靜態屬性.
Uint8Array.BYTES_PER_ELEMENT-
返回元素大小的數字值。對於
Uint8Array,其值為1。
靜態方法
繼承了其父類 TypedArray 的靜態方法.
Uint8Array.fromBase64()-
從 base64 編碼的字串建立新的
Uint8Array物件。 Uint8Array.fromHex()-
從十六進位制編碼的字串建立新的
Uint8Array物件。
例項屬性
也繼承了其父類 TypedArray 的例項屬性.
這些屬性定義在 Uint8Array.prototype 上,並由所有 Uint8Array 例項共享。
Uint8Array.prototype.BYTES_PER_ELEMENT-
返回元素大小的數字值。對於
Uint8Array,其值為1。 Uint8Array.prototype.constructor-
建立例項物件的建構函式。對於
Uint8Array例項,初始值為Uint8Array建構函式。
例項方法
繼承了其父類 TypedArray 的例項方法.
Uint8Array.prototype.setFromBase64()-
使用 base64 編碼字串中的位元組填充此
Uint8Array物件,並返回一個指示已讀取和寫入位元組數 Object。 Uint8Array.prototype.setFromHex()-
使用十六進位制編碼字串中的位元組填充此
Uint8Array物件,並返回一個指示已讀取和寫入位元組數 Object。 Uint8Array.prototype.toBase64()-
根據此
Uint8Array物件中的資料返回 base64 編碼的字串。 Uint8Array.prototype.toHex()-
根據此
Uint8Array物件中的資料返回十六進位制編碼的字串。
示例
建立 Uint8Array 的不同方法
// From a length
const uint8 = new Uint8Array(2);
uint8[0] = 42;
console.log(uint8[0]); // 42
console.log(uint8.length); // 2
console.log(uint8.BYTES_PER_ELEMENT); // 1
// From an array
const x = new Uint8Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Uint8Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(8);
const z = new Uint8Array(buffer, 1, 4);
console.log(z.byteOffset); // 1
// From an iterable
const iterable = (function* () {
yield* [1, 2, 3];
})();
const uint8FromIterable = new Uint8Array(iterable);
console.log(uint8FromIterable);
// Uint8Array [1, 2, 3]
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-typedarray-objects |
瀏覽器相容性
載入中…