参见英文答案 > Why is creating a Float32Array with an offset that isn’t a multiple of the element size not allowed? 2个
> Strange limitation in ArrayBufferView constructor 1个
在typed array specification中,有一个构造函数允许获取现有的ArrayBuffer并将其视为另一个数组类型.有趣的是,offset参数必须是构造数组的基础类型的倍数.这种限制的原因是什么?
对于背景 – 我试图编码通过WebSocket发送的二进制缓冲区.缓冲区包含不同大小的各种变量.最初我想使用以下代码:
var buffer = new ArrayBuffer(10);
new Uint32Array(buffer,1)[0] = 234;
new Int16Array(buffer,4,1)[0] = -23;
new Uint32Array(buffer,6,1)[0] = 6000; // Exception is raised here,// because 6 is not multiple of 4
为了完成这项工作,我需要重写最后一行,如下所示:
var tempArray = new Uint32Array(1); // Create 32-bit array
tempArray[0] = 6000; // Write 32-bit number
var u8Src = new Uint8Array(tempArray,0); // Create 8-bit view of the array
var u8Dest = new Uint8Array(buffer,4); // Create 8-bit view of the buffer
u8Dest.set(u8Src); // Copy bytes one by one
对于这种简单的操作来说,这是太多的代码.
最佳答案