最簡單的條件判斷是if語句,語法是 if(condition){ do this … }
。條件判斷為真,才執(zhí)行分支中的代碼。舉個字符串的例子:
var country = 'France';
var weather;
var food;
var currency;
if(country === 'England') {
weather = 'horrible';
food = 'filling';
currency = 'pound sterling';
}
if(country === 'France') {
weather = 'nice';
food = 'stunning, but hardly ever vegetarian';
currency = 'funny, small and colourful';
}
if(country === 'Germany') {
weather = 'average';
food = 'wurst thing ever';
currency = 'funny, small and colourful';
}
var message = 'this is ' + country + ', the weather is ' +
weather + ', the food is ' + food + ' and the ' +
'currency is ' + currency;
注意: 條件判斷可以嵌套。
{% exercise %}
填寫 name
的值,驗證條件判斷。
{% initial %}
var name =
if (name === "John") {
} {% solution %} var name = "John";
if (name === "John") {
} {% validation %} assert(name === "John"); {% endexercise %}