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 |
浏览器兼容性
加载中…