调整ArrayBuffer的大小

时间:2013-09-03 20:26:50

标签: javascript arrays

如果我想创建一个数组缓冲区,我写道:var buff = new ArrayBuffer(size)

但是如何调整现有缓冲区的大小呢?我的意思是,在缓冲区的末尾添加更多的字节。

5 个答案:

答案 0 :(得分:11)

ArrayBuffer本身没有设置。但是TypedArray上有set。使用方式如下:

var oldBuffer = new ArrayBuffer(20);

var newBuffer = new ArrayBuffer(40);
new Uint8Array(newBuffer).set(oldBuffer);

答案 1 :(得分:6)

你不能。

From the MDN

  

ArrayBuffer是一种用于表示泛型的数据类型,   固定长度二进制数据缓冲区。

我不知道你尝试做什么,但显然你没有使用它们如何使用它们。

This page是学习如何在JavaScript中使用类型化数组的一个很好的起点。

答案 2 :(得分:4)

您正在寻找的是“设定”方法。创建一个新的更大的数组后,只需调用set函数并复制旧的内容。

答案 3 :(得分:4)

这样做的方式是ArrayBuffer.transfer(oldBuffer, newByteLength),如下所示:

var buffA = new ArrayBuffer(30);
var buffB = ArrayBuffer.transfer(buffA, 40);

// buffA is now an empty array buffer (`buffA.byteLength === 0`)
// whereas buffB is a new buffer that starts with a's contents
// and ends with 10 bytes that are 0s.

// Much faster than manually copying. You could even just do:

var buffA = new ArrayBuffer(30);
buffA = ArrayBuffer.transfer(buffA, 40);

// Or as a prototype method

ArrayBuffer.prototype.resize = function(newByteLength) {
    return ArrayBuffer.transfer(this, newByteLength);
}

var buffA = new ArrayBuffer(30);
buffA = buffA.resize(40);

但是(截至2017年10月)有0%的浏览器支持(甚至不支持Node.js),甚至还没有起草。

在此可用之前,您可以使用页面上给出的polyfill,它一次复制8个字节,因此对于大型数组来说相对较快(尽管它不会清空给定的数组,这是不可能的)。

以下是使用TypeArray.prototype.set而不是for循环的修改版本:

if (!ArrayBuffer.transfer) {
  ArrayBuffer.transfer = function(oldBuffer, newByteLength) {
    var srcBuffer = Object(oldBuffer);
    var destBuffer = new ArrayBuffer(newByteLength);
    if (!(srcBuffer instanceof ArrayBuffer) || !(destBuffer instanceof ArrayBuffer)) {
      throw new TypeError('Source and destination must be ArrayBuffer instances');
    }
    var copylen = Math.min(srcBuffer.byteLength, destBuffer.byteLength);

    /* Copy 8 bytes at a time */
    var length = Math.trunc(copylen / 64);
    (new Float64Array(destBuffer, 0, length))
      .set(new Float64Array(srcBuffer, 0, length));

    /* Copy the remaining 0 to 7 bytes, 1 byte at a time */
    var offset = length * 64;
    length = copylen - offset;
    (new Uint8Array(srcBuffer, offset, length))
      .set(new Uint8Array(destBuffer, offset, length));

    return destBuffer;
  };
}

答案 4 :(得分:-4)

var buff = new ArrayBuffer(32);
buff[31] = 43;
var newBuff = new ArrayBuffer(buff.byteLength*2);

for (var i=0;i<buff.byteLength;i++){
    newBuff[i] = buff[i];
}

buff = newBuff;

我是用C ++这样做的。刚制作一个更大的数组并复制内容,然后返回更大的数组并将其设置为原始数组。