如何简化嵌套条件?

use*_*367 2 javascript arrays if-statement object

我认为使用 if / if else 语句代码太多,我在一些网站上看到可以更好地简化嵌套条件,例如本网站上显示的一些示例 https://www.javascripttutorial.net/javascript-if-else/

我想在数组或这样的对象中获取风向名称 - let windNames = [Northerly','North Easterly','Easterly','South Easterly'...]

你们能帮我吗?

非常感谢。

function textDescription(d) {
    { //convert the wind direction as int to string
        if (d > 0 && d < 20) {
            return "Northerly";
        } else if (d > 30 && d < 60) {
            return "North easterly";
        } else if (d > 55 && d < 100) {
            return "Easterly";
        } else if (d > 110 && d < 140) {
            return "South easterly";
        } else if (d > 145 && d < 201) {
            return "Southerly";
        } else if (d > 201 && d < 215) {
            return "South westerly";
        } else if (d > 235 && d < 245) {
            return "Westerly";
        } else if (d > 225 && d < 325) {
            return "North westerly";
        } else if (d > 321) {
            return "Northerly";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 6

您可以使用数组数组,其中每个子数组表示两个数字d必须介于两者之间,以及相关联的字符串。当函数被调用时,.find关联子数组,如果存在则返回其字符串:

const windDirections = [
  [0, 20, 'Northerly'],
  [30, 60, 'North easterly'],
  [55, 100, 'Easterly'],
  [110, 140, 'South easterly'],
  [145, 201, 'Southerly'],
  [201, 215, 'South westerly'],
  [235, 245, 'Westerly'],
  [225, 325, 'North westerly'],
  [321, Infinity, 'Northerly'],
];
function textDescription(d) {
  const foundDirectionArr = windDirections.find(([low, high]) => d > low && d < high);
  if (foundDirectionArr) {
    return foundDirectionArr[2];
  }
}

console.log(textDescription(208));
console.log(textDescription(326));
Run Code Online (Sandbox Code Playgroud)

  • 类似的东西会更优雅,但只有方向范围均匀时才有可能 - 但事实并非如此,它们非常不均匀。一个范围是 20,另一个范围是 30,另一个 45,另一个 56,另一个 14,等等...现在,如果它们都是 45 或类似的值,那么这种通用方法就可以工作 (2认同)