JavaScript中如何合并多个DataView二进制视图对象?
实现方案
DataView本身没有内置的拼接方法,你需要先将两个DataView对应的二进制内容拷贝到新的连续内存空间,再基于新的内存生成合并后的DataView,具体实现代码如下:
// 先修正原代码的语法问题(多余的右括号) const a = (await device1.transferIn(1, 64)).data; const b = (await device2.transferIn(1, 64)).data; // 合并逻辑 const totalByteLength = a.byteLength + b.byteLength; const mergedUint8 = new Uint8Array(totalByteLength); // 写入第一个DataView的内容 mergedUint8.set(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), 0); // 写入第二个DataView的内容,偏移量为第一个DataView的长度 mergedUint8.set(new Uint8Array(b.buffer, b.byteOffset, b.byteLength), a.byteLength); // 生成最终的合并DataView const c = new DataView(mergedUint8.buffer);
注意:创建Uint8Array时指定byteOffset和byteLength是为了兼容DataView仅引用底层ArrayBuffer部分区间的场景,避免把不属于当前DataView的冗余数据拷贝进来,如果你确认两个DataView都对应完整的底层ArrayBuffer,可以简化掉这两个参数。
内容的提问来源于stack exchange,提问作者user5507535
相关产品推荐
相关产品推荐

