如何合并Uint8Arrays数组?

问题描述 投票:1回答:1

我有几个Uint8Arrays的数组。与此类似的东西:

[Uint8Array(16384), Uint8Array(16384), Uint8Array(16384), Uint8Array(16384), Uint8Array(16384), Uint8Array(8868)]

如何将它们合并/连接(不确定正确的术语)到单个ArrayBuffer?

这里的关键是我需要的输出必须是ArrayBuffer。

javascript arrays typed-arrays
1个回答
3
投票

您可以使用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);
© www.soinside.com 2019 - 2024. All rights reserved.