获得该代码:
function orderMyLogic(val) {
if (val < 10) {
return "Less than 10";
} else if (val < 5) {
return "Less than 5";
} else {
return "Greater than or equal to 10";
}
}
console.log(orderMyLogic(7));
console.log(orderMyLogic(4));
console.log(orderMyLogic(11));
结果是
Less than 10
Less than 10
Greater than or equal to 10
我理解为什么会这样,但是语法上有哪些选项(如果有) 我可以接受,这样他们的结果将与下面的代码相同 而不更改(val <10)和(val <5)的位置
function orderMyLogic(val) {
if (val < 5) {
return "Less than 5";
} else if (val < 10) {
return "Less than 10";
} else {
return "Greater than or equal to 10";
}
}
console.log(orderMyLogic(7));
console.log(orderMyLogic(4));
console.log(orderMyLogic(11));
结果将是:
Less than 10
Less than 5
Greater than or equal to 10
答案 0 :(得分:1)
对于没有if
语句的解决方案,可以将conditional (ternary) operator ?:
与值一起使用。
function orderMyLogic(val) {
return val < 5
? "Less than 5"
: val < 10
? "Less than 10"
: "Greater than or equal to 10";
}
console.log(orderMyLogic(7));
console.log(orderMyLogic(4));
console.log(orderMyLogic(11));