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提前跳出函數(shù)
只要 JavaScript 解釋器在函數(shù)中遇到 return,它就會(huì)跳出函數(shù),即使函數(shù)體中還有代碼沒有執(zhí)行窃这。
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"
使用多個(gè)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"