切片JavaScript TypedArray多次

我试图将一个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,如果我replace第一行:

 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]) 

为什么这种行为?

types化数组slice方法的第二个参数是结束点,而不是切片的长度(常规非types数组切片的作用相同)。

来自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 } }