javascript 如何合并Uint8Arrays数组?

hgqdbh6s  于 2023-02-07  发布在  Java
关注(0)|答案(6)|浏览(922)

我有一个由几个Uint 8Arrays组成的数组,类似于:
[Uint8Array(16384), Uint8Array(16384), Uint8Array(16384), Uint8Array(16384), Uint8Array(16384), Uint8Array(8868)]
如何将它们合并/连接/联接(不确定哪个术语正确)到单个ArrayBuffer?
这里的关键是我需要的输出必须是一个ArrayBuffer。

gmxoilav

gmxoilav1#

可以使用set方法,创建一个新的类型化数组,包含所有大小。示例:

var arrayOne = new Uint8Array([2,4,8]);
var arrayTwo = new Uint8Array([16,32,64]);

var mergedArray = new Uint8Array(arrayOne.length + arrayTwo.length);
mergedArray.set(arrayOne);
mergedArray.set(arrayTwo, arrayOne.length);

备选方案:将类型化数组转换为"普通"数组。将其连接并再次创建一个类型化数组。
在您的情况下(解决方案):

let myArrays = [new Uint8Array(16384), new Uint8Array(16384), new Uint8Array(16384), new Uint8Array(16384), new Uint8Array(16384), new Uint8Array(8868)];

// Get the total length of all arrays.
let length = 0;
myArrays.forEach(item => {
  length += item.length;
});

// Create a new array with total length and merge all source arrays.
let mergedArray = new Uint8Array(length);
let offset = 0;
myArrays.forEach(item => {
  mergedArray.set(item, offset);
  offset += item.length;
});

// Should print an array with length 90788 (5x 16384 + 8868 your source arrays)
console.log(mergedArray);
p4rjhz4m

p4rjhz4m2#

就像对待普通数组一样:

var concatArray = new Uint8Array([ ...Uint8Array1, ...Uint8Array2, ...Uint8Array3 ]);
nkcskrwz

nkcskrwz3#

您可以使用一个helper函数来按照提供的顺序连接任意长度数组的数组。
这看起来很好很简洁,但由于spread运算符,它也会在每次迭代时复制acc

// arrays are Uint8Array[]
(arrays) => new Uint8Array(arrays.reduce((acc, curr) => [...acc, ...curr], []));

这看起来有点长,但是性能更好,因为acc不是在每个迭代上展开,而是推送到并返回:

// arrays are Uint8Array[]
(arrays) => {
  const flatNumberArray = arrays.reduce((acc, curr) => {
    acc.push(...curr);
    return acc;
  }, []);

  return new Uint8Array(flatNumberArray);
};
pinkon5k

pinkon5k4#

这对我很有效:single_array就是您想要的

var arrays = [Uint8Array(16384), Uint8Array(16384), Uint8Array(16384), Uint8Array(16384), Uint8Array(16384), Uint8Array(8868)]


 var single_array = concat(arrays)

function concat(arrays) {
  // sum of individual array lengths
  let totalLength = arrays.reduce((acc, value) => acc + value.length, 0);

  if (!arrays.length) return null;

   let result = new Uint8Array(totalLength);

      // for each array - copy it over result
      // next array is copied right after the previous one
      let length = 0;
      for(let array of arrays) {
            result.set(array, length);
            length += array.length;
      }

      return result;
   }
gojuced7

gojuced75#

基于Dominik答案的函数:

function mergeUInt8Arrays(a1: Uint8Array, a2: Uint8Array): Uint8Array {
  // sum of individual array lengths
  var mergedArray = new Uint8Array(a1.length + a2.length);
  mergedArray.set(a1);
  mergedArray.set(a2, a1.length);
  return mergedArray;
}
disho6za

disho6za6#

有一个简单的方法:

await new Blob([a1,a2,a3]).arraybuffer();

但那时候很慢

new Uint8Array(a1.length + a2.length + a3.length)
..set(a1,0)
..set(a2,a1.length)
..set(a3,a1.length+a2.length)

相关问题