【问题标题】:How to flatten a Float32Array in JS?如何在 JS 中展平 Float32Array?
【发布时间】:2021-10-19 17:29:48
【问题描述】:

我有一个充满Float32Arrays 的数组,如下所示:

var arr = [
  new Float32Array([0.3, 0.7, 0.1]),
  new Float32Array([0.2, 0.544, 0.21]),
];

console.log(arr.flat(Infinity));

我如何将它们压扁成这样?:

[0.3, 0.7, 0.1, 0.2, 0.544, 0.21]

我尝试过使用Array.flat(Infinity),但这仍然使Float32Arrays 保持不变。

【问题讨论】:

标签: javascript


【解决方案1】:

例如

let arr = [
  new Float32Array([0.3, 0.7, 0.1]),
  new Float32Array([0.2, 0.544, 0.21]),
];

arr = arr.map(a => [...a]).flat();

console.log(arr);

【讨论】:

    【解决方案2】:

    const arr = [ new Float32Array([0.3, 0.7, 0.1]), new Float32Array([0.2, 0.544, 0.21])];
    
    const arr3 =  arr.map(float32Array => Array.from(float32Array));
    console.log(arr3.flat()); 
    /*
    ^output
    [
      0.30000001192092896,
      0.699999988079071,
      0.10000000149011612,
      0.20000000298023224,
      0.5440000295639038,
      0.20999999344348907
    ]
    */
    
    //rounded to three decimal points
    const arr2 =  arr.map(float32Array => Array.from(float32Array).map(float32 => Math.round(float32 * 1000) / 1000));
    console.log(arr2.flat()); //--> [0.3, 0.7, 0.1, 0.2, 0.544, 0.21]

    【讨论】:

      【解决方案3】:

      可以-

      var arr = [
        new Float32Array([0.3, 0.7, 0.1]),
        new Float32Array([0.2, 0.544,0.21]),
      ];
      
      console.log(Array.from(arr[0]).concat(Array.from(arr[1])));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-29
        • 1970-01-01
        • 2021-06-19
        • 1970-01-01
        • 1970-01-01
        • 2016-06-20
        相关资源
        最近更新 更多