如何在javascript中将字节,多字节和缓冲区附加到ArrayBuffer?

cod*_*eto 15 javascript buffer typed-arrays arraybuffer

Javascript ArrayBuffer或TypedArrays没有任何类型的appendByte(),appendBytes()或appendBuffer()方法.因此,如果我想一次填充一个ArrayBuffer值,我该怎么做?

var firstVal = 0xAB;              // 1 byte
var secondVal = 0x3D7F            // 2 bytes
var anotherUint8Array = someArr;

var buffer = new ArrayBuffer();   // I don't know the length yet
var bufferArr = new UInt8Array(buffer);

// following methods do not exist. What are the alternatives for each??
bufferArr.appendByte(firstVal);
bufferArr.appendBytes(secondVal);
bufferArr.appendBuffer(anotherUint8Array);
Run Code Online (Sandbox Code Playgroud)

Pau*_* S. 13

您可以使用新的ArrayBuffer创建新的TypedArray,但不能更改现有缓冲区的大小

function concatTypedArrays(a, b) { // a, b TypedArray of same type
    var c = new (a.constructor)(a.length + b.length);
    c.set(a, 0);
    c.set(b, a.length);
    return c;
}
Run Code Online (Sandbox Code Playgroud)

现在可以做到

var a = new Uint8Array(2),
    b = new Uint8Array(3);
a[0] = 1; a[1] = 2;
b[0] = 3; b[1] = 4;
concatTypedArrays(a, b); // [1, 2, 3, 4, 0] Uint8Array length 5
Run Code Online (Sandbox Code Playgroud)

如果你想使用不同的类型,请选择via,Uint8Array因为最小的单位是一个字节,即

function concatBuffers(a, b) {
    return concatTypedArrays(
        new Uint8Array(a.buffer || a), 
        new Uint8Array(b.buffer || b)
    ).buffer;
}
Run Code Online (Sandbox Code Playgroud)

这意味着.length将按预期工作,您现在可以将其转换为您选择的类型数组(确保它是一个接受.byteLength缓冲区的类型)


从这里开始,您现在可以实现任何您喜欢的方法来连接数据,例如

function concatBytes(ui8a, byte) {
    var b = new Uint8Array(1);
    b[0] = byte;
    return concatTypedArrays(ui8a, b);
}

var u8 = new Uint8Array(0);
u8 = concatBytes(u8, 0x80); // [128]
Run Code Online (Sandbox Code Playgroud)


new*_*guy 6

Paul 的回答允许您将一个 TypedArray 连接到一个现有的 TypedArray。在 ES6 中,您可以使用以下函数连接多个 TypedArray:

function concatenate(resultConstructor, ...arrays) {
    let totalLength = 0;
    for (const arr of arrays) {
        totalLength += arr.length;
    }
    const result = new resultConstructor(totalLength);
    let offset = 0;
    for (const arr of arrays) {
        result.set(arr, offset);
        offset += arr.length;
    }
    return result;
}

const ta = concatenate(Uint8Array,
    Uint8Array.of(1, 2), Uint8Array.of(3, 4));
console.log(ta); // Uint8Array [1, 2, 3, 4]
console.log(ta.buffer.byteLength); // 4
Run Code Online (Sandbox Code Playgroud)

追加一个新字节是:

const byte = 3;
concatenate(Uint8Array, Uint8Array.of(1, 2), Uint8Array.of(byte));
Run Code Online (Sandbox Code Playgroud)

这个方法可以在ExploringJS 中找到。