【问题标题】:determining range of values of TypedArray item确定 TypedArray 项的值范围
【发布时间】:2016-10-27 01:21:53
【问题描述】:

根据the documentation on the Uint8ClampedArray,

Uint8ClampedArray 类型数组表示一个 8 位无符号整数数组,限制在 0-255;如果您指定的值超出 [0,255] 的范围,将改为设置 0 或 255。

其他TypedArrays 功能类似。给定列出的类型中的任何类型数组,有没有办法以编程方式导出可能存储在其中的最大/最小值?

类似的东西:

Uint8ClampedArray().maxItemValue // returns 255

【问题讨论】:

  • BYTES_PER_ELEMENT 可能会有所帮助,但您仍然需要区分有符号和无符号类型。
  • 是的,我也看到了……在 name 属性上执行 switch 语句最终可能是最有效的,但最好不必这样做。
  • 为什么在.name 属性上?如果需要,您可以自行打开功能。
  • 你想要 every 类型的最大值(甚至是浮点数)吗?你也想要最小值(对于签名类型)吗?
  • TypedArray 可能包含的每种类型,最小值和最大值,是的。

标签: javascript web-frontend


【解决方案1】:

我会使用以下内容:

function maxElementValue(arr) {
    const c = arr.constructor;
    const test = c.of(-1.5)[0];
    if (test > 0) // unsigned integers
        return test;
    //  return 0xFFFFFFFF >>> (32 - 8 * c.BYTES_PER_ELEMENT);
    //  return Math.pow(2, 8 * c.BYTES_PER_ELEMENT) - 1;
    if (test == -1) // signed integers
        return 0x7FFFFFFF >>> (32 - 8 * c.BYTES_PER_ELEMENT);
    //  return Math.pow(2, 8 * c.BYTES_PER_ELEMENT - 1) - 1;
    if (test == 0) // clamped
        return 0xFF; // there's only one of these
    if (test == -1.5)
        throw new TypeError("floats are not supported");
    throw new TypeError("weirdly behaving typed array");
}

【讨论】:

  • 不错!这似乎按预期工作。我认为我可以自己算出最小值部分。
猜你喜欢
  • 1970-01-01
  • 2010-10-25
  • 2014-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-06
  • 2021-07-02
  • 1970-01-01
相关资源
最近更新 更多