如果我想检查相同的值是否等于多个不同的值,并且每次都有不同的结果,例如(例如):

var someArray = new (
    max - min < 128 ? Int8Array :
    max - min < 256 ? Uint8Array :
    max - min < 32768 ? Int16Array :
    max - min < 65536 ? Uint16Array :
    max - min < 2147483648 ? Int32Array :
    max - min < 4294967296 ? Uint32Array :
    Array
)


我需要每次(最大-最小)重写值,即使它是单个变量,也仍然需要重复。有什么方法可以只写一次该值但得到相同的结果,例如:

var someArray = new (
        inlineSwitch(max - min) $$ //just an example symbol
        < 128 ? Int8Array :
        < 256 ? Uint8Array :
        < 32768 ? Int16Array :
        < 65536 ? Uint16Array :
        < 2147483648 ? Int32Array :
        < 4294967296 ? Uint32Array
)


或者其他的东西?有什么办法可以做这样的事情吗?还是可以使某个函数接受与此类似的输入?

编辑

我在最后添加了最后一个“数组”条件,如果该条件大于任何条件,则也应考虑到这一点。速度也很重要-如果这是函数的一部分,那么比添加许多其他变量可能会使速度变慢。

最佳答案

您可以改用一个对象,该对象按数字索引,其值是关联的构造函数,然后.find相应的条目:

const constructorByNumRange = {
  128 : Int8Array,
  256: Uint8Array,
  // ...
};

const diff = max - min;
const constructorEntry = Object.entries(constructorByNumRange)
  .find(([numStr]) => Number(numStr) < diff);
const someArray = new constructorEntry[1]();


如果有可能找不到条目,​​则可以添加一个检查,以确保.find返回条目:

if (!constructorEntry) {
  // handle situation in which the diff range was not found
  throw new Error('Not found');
}


您也可以使用数组数组代替对象:

const constructorByNumRange = [
  [128, Int8Array],
  [256, Uint8Array],
  // ...
};

const diff = max - min;
const constructorEntry = constructorByNumRange
  .find(([num]) => num < diff);

关于javascript - JavaScript —内联切换语句?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55896032/

10-12 06:53