记录6 if-else、return关键字

if else

var lemonChicken = false;
var beefWithBlackBean = true;
var sweetAndSourPork = true;
if(lemonChicken){
  console.log("1");
} else if (beefWithBlackBean) {
  console.log("2");
} else if (sweetAndSourPork) {
  console.log("3")  
}  else {
  console.log("4");
}

用return提前跳出函数

只要 JavaScript 解释器在函数中遇到 return,它就会跳出函数,即使函数体中还有代码没有执行。

var fifthLetter = function (name) {
    if(name.length < 5){
        return;
    }
    return "The fifth letter of your name is " + name;
};
>>  undefined
fifthLetter("he");
>>  undefined
fifthLetter("hehehe");
>>  "The fifth letter of your name is hehehe"

使用多个return语句来代替if...else语句

var socreResult=function(score){
    if(score<3){
        return "小于3";
    }

    if(score<7){
        return "kk3<=score<7";
    }

    return "大于等于7";
};
socreResult(2);
>>  "小于3"
socreResult(5);
>>  "kk3<=score<7"
socreResult(10);
>>  "大于等于7"

推荐阅读更多精彩内容