如何在JavaScript中合并TypedArrays?

yom*_*tsu 34 javascript typed-arrays

我想合并多个arraybuffers来创建一个Blob.但是,如你所知, TypedArray没有"推"或有用的方法......

例如:

var a = new Int8Array( [ 1, 2, 3 ] );
var b = new Int8Array( [ 4, 5, 6 ] );
Run Code Online (Sandbox Code Playgroud)

结果,我想得到[ 1, 2, 3, 4, 5, 6 ].

Pri*_*orn 64

使用该set方法.但请注意,你现在需要两倍的内存!

var a = new Int8Array( [ 1, 2, 3 ] );
var b = new Int8Array( [ 4, 5, 6 ] );

var c = new Int8Array(a.length + b.length);
c.set(a);
c.set(b, a.length);

console.log(a);
console.log(b);
console.log(c);
Run Code Online (Sandbox Code Playgroud)

  • @yomotsu是的,你需要创建一个新的.如果你知道C,TypedArray类似于使用`malloc`(不需要'free`).但是没有什么比`realloc`更像了. (5认同)

Jer*_*ser 10

对于客户端 ~ok 解决方案:

const a = new Int8Array( [ 1, 2, 3 ] )
const b = new Int8Array( [ 4, 5, 6 ] )
const c = Int8Array.from([...a, ...b])
Run Code Online (Sandbox Code Playgroud)

  • @Timmmm 它仅适用于函数调用的参数。“当使用扩展语法进行函数调用时,...”和“但要注意:通过使用这种方式应用,您将面临超出 JavaScript 引擎参数长度限制的风险”,它还说“参数限制为 65536”。我已经用两个 65536 长度的 Int8Arrays 测试了传播并且它有效。 (3认同)
  • 这将遇到长度限制。您不应该将扩展运算符用于无界数据。 (2认同)
  • 这种不太详细的解决方案的唯一缺点是它创建了一个中间_array_而不是类型化数组。无论如何,对于较短的数组,这不会成为问题。 (2认同)

Dän*_*änu 6

我总是使用这个功能:

function mergeTypedArrays(a, b) {
    // Checks for truthy values on both arrays
    if(!a && !b) throw 'Please specify valid arguments for parameters a and b.';  

    // Checks for truthy values or empty arrays on each argument
    // to avoid the unnecessary construction of a new array and
    // the type comparison
    if(!b || b.length === 0) return a;
    if(!a || a.length === 0) return b;

    // Make sure that both typed arrays are of the same type
    if(Object.prototype.toString.call(a) !== Object.prototype.toString.call(b))
        throw 'The types of the two arguments passed for parameters a and b do not match.';

    var c = new a.constructor(a.length + b.length);
    c.set(a);
    c.set(b, a.length);

    return c;
}
Run Code Online (Sandbox Code Playgroud)

原始函数不检查null或类型

function mergeTypedArraysUnsafe(a, b) {
    var c = new a.constructor(a.length + b.length);
    c.set(a);
    c.set(b, a.length);

    return c;
}
Run Code Online (Sandbox Code Playgroud)