javascript - 如何用更简单的表达式替换多个 if else

我已经定义了多个区间 [0, 20[,[20, 70[, [70, 200[, [200, 500[, [500, 10000[, [1000, infinity[。对于给定的 x 的 value,我们在 [0,1,2,3,4,5] 中得到一个 value y,其中 [0, 20[ 对应于 0 等...基本解决方案是使用 if 语句喜欢:

if (x>=0 && x<20){
  y = 0
} 
if (x>=20 && x<70){
  y = 1
}
.
.
.

此任务是否有其他解决方案(更少代码)?我在nodejs中使用这段代码

回答1

使用 else if,那么你不需要检查下限,因为之前的检查已经处理了。

if (x < 20) {
    y = 0;
} else if (x < 70) {
    y = 1;
} ...

或者您可以将限制放在一个数组中,然后循环直到超过限制。

const limits = [20, 70, 200, ...];
let y;
for (y = 0; y < limits.length && x < limits[y]; y++) {};

回答2

你可以使用这样的逻辑:

const intervals = [
    { from: 0, to: 20},
    { from: 20, to: 70},
    { from: 70, to: 200},
    { from: 200, to: 500},
    { from: 500, to: 1000},
    { from: 1000, to: Number.POSITIVE_INFINITY}
];

function findInterval(x) {
    for (let i in intervals) {
        if (x >= intervals[i].from && x < intervals[i].to) {
            return i;
        }
    }
    throw new Error('Argument not within intervals');
}

// test:
const testvalues = [5, 21, 90, 345, 878, 9234802];
for (let x of testvalues) {
    console.log(`interval of ${x}: ` + findInterval(x));
}

// output:
interval of 5: 0
interval of 21: 1
interval of 90: 2
interval of 345: 3
interval of 878: 4
interval of 9234802: 5

回答3

你可以试试这个

const ranges = [
  [0, 20],
  [20, 70],
  [70, 200],
  [200, 500],
  [500, 10000],
  [1000, Infinity]
];

function getIntersectionIndex(x) {
  for (let i = 0; i < ranges.length; i++) {
    if (ranges[i][0] <= x && x < ranges[i][1])
      return i;
  }
  return -1;
}

const y = getIntersectionIndex(10); // returns 0

相似文章

javascript - 相关按钮

此测验可在计算机上运行,但当我尝试在手机上使用它时,文本变大且压缩,因此按钮停止工作。我试图将.slide更改为relative并将.buttontop-margin更改为30px,但如果.slide...

随机推荐

最新文章