确定 TypedArray 项的值范围

determining range of values of TypedArray item

根据the documentation on the Uint8ClampedArray

The Uint8ClampedArray typed array represents an array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead.

其他TypedArray的功能类似。给定所列类型中的任何类型化数组,是否有一种方法可以通过编程方式导出可能存储在其中的 max/min 值?

大致如下:

Uint8ClampedArray().maxItemValue // returns 255

我会使用以下内容:

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");
}