先決條件: | 基本的計(jì)算機(jī)素養(yǎng),對HTML和CSS的基本了解, JavaScript第一步。 |
---|---|
目的: | 了解如何在JavaScript中使用條件結(jié)構(gòu)。 |
人類(和其他動物)在影響他們生活的所有時間做決定,從小("我應(yīng)該吃一個餅干還是兩個?")到大("我應(yīng)該留在我的祖國,在我父親的農(nóng)場工作, 我應(yīng)該搬到美國,研究天體物理學(xué)嗎?")
條件語句允許我們在JavaScript中表示這樣的決策,從必須做出的選擇(例如"一個或兩個")到所得到的結(jié)果或那些選擇(或許"吃一個cookie"的結(jié)果可能是"仍然 感覺饑餓","吃兩個餅干"的結(jié)果可能"感覺充滿了,但媽媽罵我吃所有的餅干"。)
讓我們來看看你將在JavaScript中使用的最常見類型的條件語句 - 謙遜 /Statements/if...else\">if ... else
語句/ if ... else">語句。
基本 if ... else
語法如下所示: pseudocode :
if (condition) { code to run if condition is true } else { run some other code instead }
這里我們有:
if
followed by some parentheses.true
or false
.true
.else
.true
.此代碼是非常易讀的 - 它是說"如果 條件返回 true
,運(yùn)行代碼A, >運(yùn)行代碼B"
你應(yīng)該注意,你不必包括 else
和第二個花括號塊 - 以下也是完美的法律代碼:
if (condition) { code to run if condition is true } run some other code
但是,你需要在這里小心 - 在這種情況下,第二個代碼塊不受條件語句控制,所以它將總是運(yùn)行,無論條件是否返回 true / code>或
false
。 這不一定是壞事,但它可能不是你想要的 - 通常你會想運(yùn)行一個代碼塊或另一個,而不是兩者。
作為最后一點(diǎn),有時可能會看到 if ... else
語句寫入沒有花括號,以下面的縮寫樣式:
if (condition) code to run if condition is true else run some other code instead
這是完全有效的代碼,但是不推薦使用它 - 更容易閱讀代碼,并解決發(fā)生了什么,如果你使用花括號來分隔代碼塊,并使用多行和縮進(jìn)。
為了更好地理解這個語法,讓我們考慮一個真實(shí)的例子。 想象一個孩子被他們的母親或父親請求幫忙做家務(wù)。 父母可能會說"嗨甜心,如果你幫助我去購物,我會給你一些額外的津貼,所以你可以買得起你想要的玩具。 在JavaScript中,我們可以這樣表示:
var shoppingDone = false; if (shoppingDone === true) { var childsAllowance = 10; } else { var childsAllowance = 5; }
如圖所示的代碼總是導(dǎo)致 shoppingDone
變量返回 false
,這意味著我們可憐的孩子會失望。 如果孩子做了購物,那么應(yīng)該由我們提供一個機(jī)制讓父母將 shoppingDone
變量設(shè)置為 true
。
注意:您可以查看更多 ="external">此示例的完整版本在GitHub (也看到它 running live 。)
最后一個例子為我們提供了兩個選擇或結(jié)果 - 但是如果我們想要兩個以上呢?
有一種方法可以將額外的選擇/結(jié)果鏈接到你的 if ... else
- 使用 else if
。 每個額外的選擇需要一個額外的塊放在 if(){...}
和 else {...}
之間 - 檢查下面更多涉及的例子, 可以是簡單的天氣預(yù)報(bào)應(yīng)用程序的一部分:
<label for="weather">Select the weather type today: </label> <select id="weather"> <option value="">--Make a choice--</option> <option value="sunny">Sunny</option> <option value="rainy">Rainy</option> <option value="snowing">Snowing</option> <option value="overcast">Overcast</option> </select> <p></p>
var select = document.querySelector('select'); var para = document.querySelector('p'); select.addEventListener('change', setWeather); function setWeather() { var choice = select.value; if (choice === 'sunny') { para.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.'; } else if (choice === 'rainy') { para.textContent = 'Rain is falling outside; take a rain coat and a brolly, and don\'t stay out for too long.'; } else if (choice === 'snowing') { para.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.'; } else if (choice === 'overcast') { para.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.'; } else { para.textContent = ''; } }
<select>
element allowing us to make different weather choices, and a simple paragraph.<select>
and <p>
elements, and adding an event listener to the <select>
element so that when its value is changed, the setWeather()
function is run.choice
to the current value selected in the <select>
element. We then use a conditional statement to show different text inside the paragraph depending on what the value of choice
is. Notice how all the conditions are tested in else if() {...}
blocks, except for the first one, which is tested in an if() {...} block
.else {...}
block, is basically a "last resort" option — the code inside it will be run if none of the conditions are true
. In this case, it serves to empty the text out of the paragraph if nothing is selected, for example if a user decides to re-select the "--Make a choice--" placeholder option shown at the beginning.注意:您還可以 ="external">在GitHub上找到此示例( "外部">看到它運(yùn)行實(shí)時也有)。
比較運(yùn)算符用于測試條件語句中的條件。 我們首先查看了 JavaScript - 數(shù)字和運(yùn)算符的基本數(shù)學(xué)文章中的比較運(yùn)算符。 我們的選擇是:
===
and !==
?— test if one value is identical to, or not identical to, another.<
and >
— test if one value is less than or greater than another.<=
and >=
— test if one value is less than or equal to, or greater than or equal to, another.Note: Review the material at the previous link if you want to refresh your memories on these.\">
我們想特別提到測試布爾( true
/ false
)值,以及一個常見的模式,你會反復(fù)遇到。 任何不是 false
, undefined
, null
, 0
, NaN
或者測試為條件語句時,空字符串(\'\'
)實(shí)際返回 true
,因此您可以簡單地使用變量名來測試它是否 > true
,或者甚至它存在(即它不是未定義的。)所以例如:
var cheese = 'Cheddar'; if (cheese) { console.log('Yay! Cheese available for making cheese on toast.'); } else { console.log('No cheese on toast for you today.'); }
并且,回到我們以前的例子,關(guān)于孩子為他們的父母做雜事,你可以這樣寫:
var shoppingDone = false; if (shoppingDone) { // don't need to explicitly specify '=== true' var childsAllowance = 10; } else { var childsAllowance = 5; }
將一個如果... else
語句放在另一個 - 中來嵌套它是完全正確的。 例如,我們可以更新我們的天氣預(yù)報(bào)應(yīng)用程序,根據(jù)溫度是什么顯示更多的選擇:
if (choice === 'sunny') { if (temperature < 86) { para.textContent = 'It is ' + temperature + ' degrees outside — nice and sunny. Let\'s go out to the beach, or the park, and get an ice cream.'; } else if (temperature >= 86) { para.textContent = 'It is ' + temperature + ' degrees outside — REALLY HOT! If you want to go outside, make sure to put some suncream on.'; } }
即使代碼一起工作,每個 if ... else
語句完全獨(dú)立于另一個工作。
如果要測試多個條件而不編寫嵌套的 if ... else
語句, / Operators / Logical_Operators">邏輯運(yùn)算符可以幫助您。 當(dāng)在條件下使用時,前兩個操作如下:
&&
— AND; allows you to chain together two or more expressions so that all of them have to individually evaluate to true
for the whole expression to return true
.||
— OR; allows you to chain together two or more expressions so that one or more of them have to individually evaluate to true
for the whole expression to return true
.為了給你一個AND示例,上面的示例代碼片段可以重寫為:
if (choice === 'sunny' && temperature < 86) { para.textContent = 'It is ' + temperature + ' degrees outside — nice and sunny. Let\'s go out to the beach, or the park, and get an ice cream.'; } else if (choice === 'sunny' && temperature >= 86) { para.textContent = 'It is ' + temperature + ' degrees outside — REALLY HOT! If you want to go outside, make sure to put some suncream on.'; }
因此,例如,第一代碼塊將僅在 choice ===\'sunny\'
和 temperature 86
return true
。
讓我們來看一個快速的OR例子:
if (iceCreamVanOutside || houseStatus === 'on fire') { console.log('You should leave the house quickly.'); } else { console.log('Probably should just stay in then.'); }
由!
運(yùn)算符表示的最后一種類型的邏輯運(yùn)算符NOT可用于否定表達(dá)式。 讓我們在上面的例子中結(jié)合OR:
if (!(iceCreamVanOutside || houseStatus === 'on fire')) { console.log('Probably should just stay in then.'); } else { console.log('You should leave the house quickly.'); }
在這個片段中,如果OR語句返回 true
,則NOT運(yùn)算符將否定它,以便整個表達(dá)式返回 false
。
您可以在任何結(jié)構(gòu)中將任意數(shù)量的邏輯語句組合在一起。 以下示例僅在兩個OR語句都返回true的情況下執(zhí)行代碼,這意味著總體AND語句將返回true:
if ((x === 5 || y > 3 || z <= 10) && (loggedIn || userName === 'Steve')) { // run the code }
在條件語句中使用邏輯OR運(yùn)算符時常見的錯誤是嘗試說明其值要被檢查一次的變量,然后給出一個值列表,它可以返回true,由 ||
>(OR)運(yùn)算符。 例如:
if (x === 5 || 7 || 10 || 20) { // run my code }
在這種情況下, if(...)
中的條件將始終評估為true,因?yàn)?(或任何其他非零值)總是評估為true。 這個條件實(shí)際上是說"如果x等于5,或7是真的 - 它總是"。 這在邏輯上不是我們想要的! 要進(jìn)行這項(xiàng)工作,你必須在每個OR運(yùn)算符的每一側(cè)指定一個完整的測試:
if (x === 5 || x === 7 || x === 10 ||x === 20) { // run my code }
if ... else
語句完成啟用條件代碼的工作,但他們不是沒有他們的缺點(diǎn)。 它們主要適用于您有幾個選擇的情況,每個都需要合理數(shù)量的代碼運(yùn)行,和/或條件復(fù)雜(例如多個邏輯運(yùn)算符)。 對于只想根據(jù)條件設(shè)置變量為某個值或打印特定語句的情況,語法可能有點(diǎn)繁瑣,尤其是如果您有大量選擇。
switch
語句是您的朋友, 它們將單個表達(dá)式/值作為輸入,然后查看多個選項(xiàng),直到找到與該值匹配的值,并執(zhí)行相應(yīng)的代碼。 這里有一些偽代碼,給你一個想法:
switch (expression) { case choice1: run this code break; case choice2: run this code instead break; // include as many cases as you like default: actually, just run this code }
這里我們有:
switch
, followed by a set of parentheses.case
, followed by a choice that the expression/value could be, followed by a colon.break
statement, followed by a semi-colon. If the previous choice matches the expression/value, the browser stops executing the code block here, and moves on to any code that appears below the switch statement.default
, followed by exactly the same code pattern as one of the cases (bullets 3–5), except that default
does not have a choice after it, and you don't need to break
statement as there is nothing to run after this in the block anyway. This is the default option that runs if none of the choices match.注意:您不必包含默認(rèn)
部分 - 如果表達(dá)式?jīng)]有機(jī)會等于未知值,您可以安全地忽略該部分。 如果有機(jī)會,但是,你需要包括它來處理未知的情況。
讓我們看一個真實(shí)的例子 - 我們將重寫我們的天氣預(yù)報(bào)應(yīng)用程序,使用switch語句:
<label for="weather">Select the weather type today: </label> <select id="weather"> <option value="">--Make a choice--</option> <option value="sunny">Sunny</option> <option value="rainy">Rainy</option> <option value="snowing">Snowing</option> <option value="overcast">Overcast</option> </select> <p></p>
var select = document.querySelector('select'); var para = document.querySelector('p'); select.addEventListener('change', setWeather); function setWeather() { var choice = select.value; switch (choice) { case 'sunny': para.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.'; break; case 'rainy': para.textContent = 'Rain is falling outside; take a rain coat and a brolly, and don\'t stay out for too long.'; break; case 'snowing': para.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.'; break; case 'overcast': para.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.'; break; default: para.textContent = ''; } }
注意:您也可以 external">在GitHub上找到此示例(請參閱 ">運(yùn)行l(wèi)ive 也有)。
在我們讓你玩一些例子之前,有一個最后一點(diǎn)語法我們想介紹給你。 三元或條件運(yùn)算符是一小部分語法,用于測試 條件并返回一個值/表達(dá)式,如果它是 true
,另一個如果是 false
- 這在某些情況下可能是有用的,并且可以占用少得多的代碼比 如果你只需要通過 true
/ false
條件選擇兩個選項(xiàng),那么 if ... else
偽代碼如下所示:
( condition ) ? run this code : run this code instead
讓我們來看一個簡單的例子:
var greeting = ( isBirthday ) ? 'Happy birthday Mrs. Smith — we hope you have a great day!' : 'Good morning Mrs. Smith.';
這里我們有一個變量 Birthday
- 如果這是 true
,我們給客人一個生日快樂消息; 如果沒有,我們給她標(biāo)準(zhǔn)的每日問候。
你不必只用三元運(yùn)算符設(shè)置變量值; 你也可以運(yùn)行函數(shù),或代碼行 - 任何你喜歡的。 以下實(shí)例顯示了一個簡單的主題選擇器,其中使用三元運(yùn)算符應(yīng)用網(wǎng)站的樣式。
<label for="theme">Select theme: </label> <select id="theme"> <option value="white">White</option> <option value="black">Black</option> </select> <h1>This is my website</h1>
var select = document.querySelector('select'); var html = document.querySelector('html'); document.body.style.padding = '10px'; function update(bgColor, textColor) { html.style.backgroundColor = bgColor; html.style.color = textColor; } select.onchange = function() { ( select.value === 'black' ) ? update('black','white') : update('white','black'); }
這里有一個 < select>
>元素來選擇主題(黑色或白色),以及一個簡單的 <
h1> 以顯示網(wǎng)站標(biāo)題。 我們還有一個稱為 update()
的函數(shù),它使用兩種顏色作為參數(shù)(輸入)。 網(wǎng)站的背景顏色設(shè)置為第一個提供的顏色,其文本顏色設(shè)置為第二個提供的顏色。
最后,我們還有一個 onchange 事件偵聽器,用于運(yùn)行 函數(shù)包含三元運(yùn)算符。 它從測試條件開始 - select.value ===\'black\'
。 如果這返回 true
,我們運(yùn)行帶有黑色和白色參數(shù)的 update()
函數(shù),這意味著我們以黑色的背景顏色和白色的文本顏色結(jié)束。 如果它返回 false
,我們運(yùn)行 update()
函數(shù),參數(shù)為白色和黑色,這意味著網(wǎng)站顏色被反轉(zhuǎn)。
注意:您也可以 external">在GitHub上找到此示例(請參閱 ">運(yùn)行l(wèi)ive 也有)。
在這個例子中,你將幫助我們完成一個簡單的日歷應(yīng)用程序。 在代碼中,你有:
<select>
element to allow the user to choose between different months.onchange
event handler to detect when the value selected in the <select>
menu is changed.createCalendar()
that draws the calendar and displays the correct month in the <h1>
element.我們需要你在 onchange
處理函數(shù)中寫一個條件語句,就在 // ADD CONDITIONAL HERE
下面。 這應(yīng)該:
choice
variable. This will be the <select>
element value after the value changes, so "January" for example.)days
to be equal to the number of days in the selected month. To do this you'll have to look up the number of days in each month of the year. You can ignore leap years for the purposes of this example.提示:
如果出錯,您可以隨時使用"重置"按鈕重置示例。 如果你真的卡住,按"顯示解決方案"看到一個解決方案。
<div class="output" style="height: 500px;overflow: auto;"> <label for="month">Select month: </label> <select id="month"> <option value="January">January</option> <option value="February">February</option> <option value="March">March</option> <option value="April">April</option> <option value="May">May</option> <option value="June">June</option> <option value="July">July</option> <option value="August">August</option> <option value="September">September</option> <option value="October">October</option> <option value="November">November</option> <option value="December">December</option> </select> <h1></h1> <ul></ul> </div> <hr> <textarea id="code" class="playable-code" style="height: 500px;"> var select = document.querySelector('select'); var list = document.querySelector('ul'); var h1 = document.querySelector('h1'); select.onchange = function() { var choice = select.value; // ADD CONDITIONAL HERE createCalendar(days, choice); } function createCalendar(days, choice) { list.innerHTML = ''; h1.textContent = choice; for (var i = 1; i <= days; i++) { var listItem = document.createElement('li'); listItem.textContent = i; list.appendChild(listItem); } } createCalendar(31,'January'); </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div>
.output * { box-sizing: border-box; } .output ul { padding-left: 0; } .output li { display: block; float: left; width: 25%; border: 2px solid white; padding: 5px; height: 40px; background-color: #4A2DB6; color: white; }
var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var code = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; updateCode(); }); solution.addEventListener('click', function() { textarea.value = jsSolution; updateCode(); }); var jsSolution = 'var select = document.querySelector(\'select\');\nvar list = document.querySelector(\'ul\');\nvar h1 = document.querySelector(\'h1\');\n\nselect.onchange = function() {\n var choice = select.value;\n var days = 31;\n if(choice === \'February\') {\n days = 28;\n } else if(choice === \'April\' || choice === \'June\' || choice === \'September\'|| choice === \'November\') {\n days = 30;\n }\n\n createCalendar(days, choice);\n}\n\nfunction createCalendar(days, choice) {\n list.innerHTML = \'\';\n h1.textContent = choice;\n for(var i = 1; i <= days; i++) {\n var listItem = document.createElement(\'li\');\n listItem.textContent = i;\n list.appendChild(listItem);\n }\n }\n\ncreateCalendar(31,\'January\');'; textarea.addEventListener('input', updateCode); window.addEventListener('load', updateCode);
在這個例子中,你將使用我們前面看到的三元運(yùn)算符示例,并將三元運(yùn)算符轉(zhuǎn)換為switch語句,這將允許我們對簡單網(wǎng)站應(yīng)用更多的選擇。 查看 < select>
- 這 時間,你會看到它沒有兩個主題選項(xiàng),但五。 您需要在 // ADD SWITCH STATEMENT
注釋下面添加一個switch語句:
choice
variable as its input expression.update()
function should be run, and be passed two color values, the first one for the background color, and the second one for the text color. Remember that color values are strings, so need to be wrapped in quotes.如果出錯,您可以隨時使用"重置"按鈕重置示例。 如果你真的卡住,按"顯示解決方案"看到一個解決方案。
<div class="output" style="height: 300px;"> <label for="theme">Select theme: </label> <select id="theme"> <option value="white">White</option> <option value="black">Black</option> <option value="purple">Purple</option> <option value="yellow">Yellow</option> <option value="psychedelic">Psychedelic</option> </select> <h1>This is my website</h1> </div> <hr> <textarea id="code" class="playable-code" style="height: 450px;"> var select = document.querySelector('select'); var html = document.querySelector('.output'); select.onchange = function() { var choice = select.value; // ADD SWITCH STATEMENT } function update(bgColor, textColor) { html.style.backgroundColor = bgColor; html.style.color = textColor; }</textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div>
var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var code = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; updateCode(); }); solution.addEventListener('click', function() { textarea.value = jsSolution; updateCode(); }); var jsSolution = 'var select = document.querySelector(\'select\');\nvar html = document.querySelector(\'.output\');\n\nselect.onchange = function() {\n var choice = select.value;\n\n switch(choice) {\n case \'black\':\n update(\'black\',\'white\');\n break;\n case \'white\':\n update(\'white\',\'black\');\n break;\n case \'purple\':\n update(\'purple\',\'white\');\n break;\n case \'yellow\':\n update(\'yellow\',\'darkgray\');\n break;\n case \'psychedelic\':\n update(\'lime\',\'purple\');\n break;\n }\n}\n\nfunction update(bgColor, textColor) {\n html.style.backgroundColor = bgColor;\n html.style.color = textColor;\n}'; textarea.addEventListener('input', updateCode); window.addEventListener('load', updateCode);
這就是你真正需要知道的JavaScript中的條件結(jié)構(gòu)現(xiàn)在! 我相信你會理解這些概念,輕松地完成這些例子; 如果您有任何不明白的地方,請隨時閱讀本文,或與我們聯(lián)系以尋求幫助。
更多建議: