复制ArrayBuffer对象最直接的方法是什么? [英] What's the most straightforward way to copy an ArrayBuffer object?

查看:515
本文介绍了复制ArrayBuffer对象最直接的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ArrayBuffer 对象,我想复制它们。虽然使用实际指针和 memcpy 这很容易,但我找不到任何直接的方法在Javascript中执行此操作。

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.

现在,这是我复制 ArrayBuffers 的方式:

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;
}

有更漂亮的方式吗?

推荐答案

ArrayBuffer 应该支持 slice (http: //www.khronos.org/registry/typedarray/specs/latest/)所以你可以尝试,

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

buffer.slice(0);

适用于Chrome 18但不适用于Firefox 10或11.至于Firefox,您需要复制它手动。您可以在Firefox中修补 slice(),因为Chrome slice()将胜过手动副本。这看起来像,

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;
    }

然后你可以打电话,

buffer.slice(0);

在Chrome和Firefox中复制数组。

to copy the array in both Chrome and Firefox.

这篇关于复制ArrayBuffer对象最直接的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆