【问题标题】:How to concat multiple Float32Arrays into one Float32Array [duplicate]如何将多个 Float32Arrays 连接成一个 Float32Array [重复]
【发布时间】:2021-05-20 09:50:38
【问题描述】:

我有一个 float32arrays 数组,并且想要一个函数将它们展平成一个大的 float 32array

const first = new Float32Array([1,2]);
const second = new Float32Array([3,4,5]);
const third = new Float32Array([6,7,8,9]);

const chunks = [first,second,third];


//this function should take an array of flaot32arrays 
//and return a new float32array which is the combination of the float32arrays in the input. 
const flattenFloat32 = (chunks) => {
  //Need code for this function
  return 

}

console.log(flattenFloat32(chunks))

【问题讨论】:

标签: javascript flatten


【解决方案1】:

啊,我找到了解决办法

const float32Flatten = (chunks) => {
    //get the total number of frames on the new float32array
    const nFrames = chunks.reduce((acc, elem) => acc + elem.length, 0)
    
    //create a new float32 with the correct number of frames
    const result = new Float32Array(nFrames);
    
    //insert each chunk into the new float32array 
    let currentFrame =0
    chunks.forEach((chunk)=> {
        result.set(chunk, currentFrame)
        currentFrame += chunk.length;
    });
    return result;
 }    

const first = new Float32Array([1,2]);
const second = new Float32Array([3,4,5]);
const third = new Float32Array([6,7,8,9]);

const chunks = [first,second,third];
console.log(float32Flatten(chunks))

【讨论】:

    【解决方案2】:

    Float32Array.of 可以接受尽可能多的参数,只要您的环境堆栈允许,因此您可以使用:

    const result = Float32Array.of(...first, ...second, ...third);
    

    const first = new Float32Array([1,2]);
    const second = new Float32Array([3,4,5]);
    const third = new Float32Array([6,7,8,9]);
    
    const result = Float32Array.of(...first, ...second, ...third);
    
    console.log(result);

    或者,您可以使用 set 函数从原始数组中设置新数组中的元素,使用 originsl 的长度作为偏移量:

    const result = new Float32Array(
        first.length + second.length + third.length
    );
    
    result.set(first, 0);
    result.set(second, first.length);
    result.set(third, first.length + second.length);
    

    const first = new Float32Array([1,2]);
    const second = new Float32Array([3,4,5]);
    const third = new Float32Array([6,7,8,9]);
    
    const result = new Float32Array(
        first.length + second.length + third.length
    );
    
    result.set(first, 0);
    result.set(second, first.length);
    result.set(third, first.length + second.length);
    
    console.log(result);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      相关资源
      最近更新 更多