2017-04-14 71 views
1

我试图拆分typedArray成小块,用这种简单的代码片段:切片的JavaScript 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]) 

为什么这种行为?

+1

因为'切片(从,到)'需要两个指数与'从<=指数&&指数 Thomas

回答

2

类型数组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 
 
    } 
 
}