arraybuffer操作,复制ArrayBuffer对象最直接的方法是什么?

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?

解决方案

ArrayBuffer is supposed to support slice (http://www.khronos.org/registry/typedarray/specs/latest/) so you can try,

buffer.slice(0);

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 Chrome slice() will outperform a manual copy. This would look something like,

if (!ArrayBuffer.prototype.slice)

ArrayBuffer.prototype.slice = function (start, end) {

var that = new Uint8Array(this);

if (end == undefined) end = that.length;

var result = new ArrayBuffer(end - start);

var resultArray = new Uint8Array(result);

for (var i = 0; i < resultArray.length; i++)

resultArray[i] = that[i + start];

return result;

}

Then you can call,

buffer.slice(0);

to copy the array in both Chrome and Firefox.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值