多次切片 JavaScript TypedArray

Slicing JavaScript TypedArray multiple times

我试图用这个简单的代码片段将 typedArray 拆分成更小的块:

const buf = new Uint8Array([0x02, 0x00, 0x07, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x00, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x61, 0x70, 0x70, 0x02])
const len = 5

for (let i=0; i<buf.length;){
  const chunk = buf.slice(i, len)
  console.log("Chunk", chunk, "from", i, "to", i + chunk.length)
  if (chunk.length) {
    i += chunk.length
  } else {
    console.log("Chunk is empty")
    break
  }
}

但我发现 slice 仅在第一次迭代时有效,在接下来的迭代中返回空块。

我注意到它也发生在 Node.js 中,如果我将第一行替换为:

const buf = Buffer.from([0x02, 0x00, 0x07, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x00, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x61, 0x70, 0x70, 0x02])

为什么会出现这种行为?

类型化数组 slice 方法的第二个参数是终点,而不是切片的长度(常规非类型化数组切片工作相同)。

From MDN:

typedarray.slice([begin[, end]])

这意味着在第二次调用时,它从 5 切片到 5,或者一个空切片。

相反,buf.slice(i, i + len).

const buf = new Uint8Array([0x02, 0x00, 0x07, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x00, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x61, 0x70, 0x70, 0x02])
const len = 5

for (let i=0; i<buf.length;){
  const chunk = buf.slice(i, i + len)
  console.log("Chunk", chunk, "from", i, "to", i + chunk.length)
  if (chunk.length) {
    i += chunk.length
  } else {
    console.log("Chunk is empty")
    break
  }
}