deno.com

操作字节数组

在处理底层数据时,我们经常会遇到以 Uint8Array 形式存在的字节数组。标准库中包含了一些常见的操作和查询方法。

让我们初始化一些字节数组
const a = new Uint8Array([0, 1, 2, 3, 4]);
const b = new Uint8Array([5, 6, 7, 8, 9]);
const c = new Uint8Array([4, 5]);
我们可以使用 concat 方法连接两个字节数组
import { concat } from "jsr:@std/bytes/concat";
const d = concat([a, b]);
console.log(d); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
有时我们需要重复某些字节
import { repeat } from "jsr:@std/bytes/repeat";
console.log(repeat(c, 4)); // [4, 5, 4, 5, 4, 5, 4, 5]
有时我们需要修改 Uint8Array 并需要一个副本
import { copy } from "jsr:@std/bytes/copy";
const cpy = new Uint8Array(5);
console.log("Bytes copied:", copy(b, cpy)); // 5
console.log("Bytes:", cpy); // [5, 6, 7, 8, 9]

使用 Deno CLI 在本地运行此示例

deno run https://docs.deno.org.cn/examples/scripts/byte_manipulation.ts

您找到所需内容了吗?

隐私政策