javascript – 是否有可能重构并完全避免使用if else else语句以获得更好的可读性

是否有可能重构并完全避免使用if else else语句以获得更好的可读性.例如 :

 function canIWatch(age) {
if (age < 6 && age > 0) return "You are not allowed to watch Deadpool after 6:00pm.";
else if (age >=6 && age < 17) return "You must be accompanied by a guardian who is 21 or older.";
else if (age >=17 && age < 25) return "You are allowed to watch Deadpool, right after you show some ID.";
else if (age >= 25 && age < 50 ) return "Yay! You can watch Deadpool with no strings attached!";
else if (age >= 50) return " You are too old to watch deadpool";
else return "Invalid age."
}

如果没有这么多if else语句,我怎么能写一个更干净的代码

最佳答案
您可以更改检查并以最小值开始并跳过else部分,因为您返回.

function canIWatch(age) {
  if (age < 0) {
      return "Invalid age."
  }
  if (age < 6) {
      return "You are not allowed to watch Deadpool after 6:00pm.";
  }
  if (age < 17) {
      return "You must be accompanied by a guardian who is 21 or older.";
  }
  if (age < 25) {
      return "You are allowed to watch Deadpool, right after you show some ID.";
  }
  if (age < 50) {
      return "Yay! You can watch Deadpool with no strings attached!";
  }
  return "You are too old to watch deadpool";
}

console.log(canIWatch(-1));
console.log(canIWatch(2));
console.log(canIWatch(8));
console.log(canIWatch(20));
console.log(canIWatch(28));
console.log(canIWatch(60));

另一种解决方案是使用带有对象的数组作为术语

function canIWatch(age) {
    var terms = [
            { age: 0, text: "Invalid age." },
            { age: 6, text: "You are not allowed to watch Deadpool after 6:00pm." },
            { age: 17, text: "You must be accompanied by a guardian who is 21 or older." },
            { age: 25, text: "You are allowed to watch Deadpool, right after you show some ID." },
            { age: 50, text: "Yay! You can watch Deadpool with no strings attached!" },
            { age: Infinity, text: "You are too old to watch deadpool" },
        ],
        text;

    terms.every(function (a) {
        text = a.text;
        return a.age <= age;
    });
    return text;
}

console.log(canIWatch(-1));
console.log(canIWatch(2));
console.log(canIWatch(8));
console.log(canIWatch(20));
console.log(canIWatch(28));
console.log(canIWatch(60));

转载注明原文:javascript – 是否有可能重构并完全避免使用if else else语句以获得更好的可读性 - 代码日志