I’m working with ArrayBuffer objects, and I would like to duplicate them. While this is rather easy with actual pointers and memcpy, I couldn’t find any straightforward way to do it in Javascript.
Right now, this is how I copy my ArrayBuffers:
function copy(buffer)
{
var bytes = new Uint8Array(buffer);
var output = new ArrayBuffer(buffer.byteLength);
var outputBytes = new Uint8Array(output);
for (var i = 0; i < bytes.length; i++)
outputBytes[i] = bytes[i];
return output;
}
Is there a prettier way?
ArrayBufferis supposed to supportslice(http://www.khronos.org/registry/typedarray/specs/latest/) so you can try,which works in Chrome 18 but not Firefox 10 or 11. As for Firefox, you need to copy it manually. You can monkey patch the
slice()in Firefox because the Chromeslice()will outperform a manual copy. This would look something like,Then you can call,
to copy the array in both Chrome and Firefox.