Making decisions in your code — conditionals

2018-05-15 17:26 更新
先決條件: 基本的計(jì)算機(jī)素養(yǎng),對(duì)HTML和CSS的基本了解, JavaScript第一步。
目的: 了解如何在JavaScript中使用條件結(jié)構(gòu)。

你可以有一個(gè)條件..!

人類(和其他動(dòng)物)在影響他們生活的所有時(shí)間做決定,從小("我應(yīng)該吃一個(gè)餅干還是兩個(gè)?")到大("我應(yīng)該留在我的祖國(guó),在我父親的農(nóng)場(chǎng)工作, 我應(yīng)該搬到美國(guó),研究天體物理學(xué)嗎?")

條件語(yǔ)句允許我們?cè)贘avaScript中表示這樣的決策,從必須做出的選擇(例如"一個(gè)或兩個(gè)")到所得到的結(jié)果或那些選擇(或許"吃一個(gè)cookie"的結(jié)果可能是"仍然 感覺饑餓","吃兩個(gè)餅干"的結(jié)果可能"感覺充滿了,但媽媽罵我吃所有的餅干"。)

if ... else語(yǔ)句

讓我們來(lái)看看你將在JavaScript中使用的最常見類型的條件語(yǔ)句 - 謙遜 /Statements/if...else\">if ... else 語(yǔ)句/ if ... else">語(yǔ)句

基本if ... else語(yǔ)法

基本 if ... else 語(yǔ)法如下所示: pseudocode :

if (condition) {
  code to run if condition is true
} else {
  run some other code instead
}

這里我們有:

  1. The keyword if followed by some parentheses.
  2. A condition to test, placed inside the parentheses (typically "is this value bigger than this other value", or "does this value exist"). This condition will make use of the comparison operators we discussed in the last module, and will return true or false.
  3. A set of curly braces, inside which we have some code — this can be any code we like, and will only be run if the condition returns true.
  4. The keyword else.
  5. Another set of curly braces, inside which we have some more code — this can be any code we like, and will only be run if the condition is not true.

此代碼是非常易讀的 - 它是說(shuō)"如果 條件返回 true ,運(yùn)行代碼A, >運(yùn)行代碼B"

你應(yīng)該注意,你不必包括 else 和第二個(gè)花括號(hào)塊 - 以下也是完美的法律代碼:

if (condition) {
  code to run if condition is true
}

run some other code

但是,你需要在這里小心 - 在這種情況下,第二個(gè)代碼塊不受條件語(yǔ)句控制,所以它將總是運(yùn)行,無(wú)論條件是否返回 true / code>或 false 。 這不一定是壞事,但它可能不是你想要的 - 通常你會(huì)想運(yùn)行一個(gè)代碼塊另一個(gè),而不是兩者。

作為最后一點(diǎn),有時(shí)可能會(huì)看到 if ... else 語(yǔ)句寫入沒有花括號(hào),以下面的縮寫樣式:

if (condition) code to run if condition is true
else run some other code instead

這是完全有效的代碼,但是不推薦使用它 - 更容易閱讀代碼,并解決發(fā)生了什么,如果你使用花括號(hào)來(lái)分隔代碼塊,并使用多行和縮進(jìn)。

一個(gè)真正的例子

為了更好地理解這個(gè)語(yǔ)法,讓我們考慮一個(gè)真實(shí)的例子。 想象一個(gè)孩子被他們的母親或父親請(qǐng)求幫忙做家務(wù)。 父母可能會(huì)說(shuō)"嗨甜心,如果你幫助我去購(gòu)物,我會(huì)給你一些額外的津貼,所以你可以買得起你想要的玩具。 在JavaScript中,我們可以這樣表示:

var shoppingDone = false;

if (shoppingDone === true) {
  var childsAllowance = 10;
} else {
  var childsAllowance = 5;
}

如圖所示的代碼總是導(dǎo)致 shoppingDone 變量返回 false ,這意味著我們可憐的孩子會(huì)失望。 如果孩子做了購(gòu)物,那么應(yīng)該由我們提供一個(gè)機(jī)制讓父母將 shoppingDone 變量設(shè)置為 true 。

注意:您可以查看更多 ="external">此示例的完整版本在GitHub (也看到它 running live 。)

否則if

最后一個(gè)例子為我們提供了兩個(gè)選擇或結(jié)果 - 但是如果我們想要兩個(gè)以上呢?

有一種方法可以將額外的選擇/結(jié)果鏈接到你的 if ... else - 使用 else if 。 每個(gè)額外的選擇需要一個(gè)額外的塊放在 if(){...} else {...} 之間 - 檢查下面更多涉及的例子, 可以是簡(jiǎn)單的天氣預(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 = '';
  }
}

  1. Here we've got an HTML <select> element allowing us to make different weather choices, and a simple paragraph.
  2. In the JavaScript, we are storing a reference to both the <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.
  3. When this function is run, we first set a variable called 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.
  4. The very last choice, inside the 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.

關(guān)于比較運(yùn)算符的注釋

比較運(yùn)算符用于測(cè)試條件語(yǔ)句中的條件。 我們首先查看了 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.\">

我們想特別提到測(cè)試布爾( true / false )值,以及一個(gè)常見的模式,你會(huì)反復(fù)遇到。 任何不是 false , undefined , null , 0 NaN 或者測(cè)試為條件語(yǔ)句時(shí),空字符串(\'\')實(shí)際返回 true ,因此您可以簡(jiǎn)單地使用變量名來(lái)測(cè)試它是否 > 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;
}

嵌套if ... else

將一個(gè)如果... else 語(yǔ)句放在另一個(gè) - 中來(lái)嵌套它是完全正確的。 例如,我們可以更新我們的天氣預(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.';
  }
}

即使代碼一起工作,每個(gè) if ... else 語(yǔ)句完全獨(dú)立于另一個(gè)工作。

邏輯運(yùn)算符:AND,OR和NOT

如果要測(cè)試多個(gè)條件而不編寫嵌套的 if ... else 語(yǔ)句, / Operators / Logical_Operators">邏輯運(yùn)算符可以幫助您。 當(dāng)在條件下使用時(shí),前兩個(gè)操作如下:

  • && — 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.

為了給你一個(gè)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 。

讓我們來(lái)看一個(gè)快速的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á)式。 讓我們?cè)谏厦娴睦又薪Y(jié)合OR:

if (!(iceCreamVanOutside || houseStatus === 'on fire')) {
  console.log('Probably should just stay in then.');
} else {
  console.log('You should leave the house quickly.');
}

在這個(gè)片段中,如果OR語(yǔ)句返回 true ,則NOT運(yùn)算符將否定它,以便整個(gè)表達(dá)式返回 false 。

您可以在任何結(jié)構(gòu)中將任意數(shù)量的邏輯語(yǔ)句組合在一起。 以下示例僅在兩個(gè)OR語(yǔ)句都返回true的情況下執(zhí)行代碼,這意味著總體AND語(yǔ)句將返回true:

if ((x === 5 || y > 3 || z <= 10) && (loggedIn || userName === 'Steve')) {
  // run the code
}

在條件語(yǔ)句中使用邏輯OR運(yùn)算符時(shí)常見的錯(cuò)誤是嘗試說(shuō)明其值要被檢查一次的變量,然后給出一個(gè)值列表,它可以返回true,由 || >(OR)運(yùn)算符。 例如:

if (x === 5 || 7 || 10 || 20) {
  // run my code
}

在這種情況下, if(...)中的條件將始終評(píng)估為true,因?yàn)?(或任何其他非零值)總是評(píng)估為true。 這個(gè)條件實(shí)際上是說(shuō)"如果x等于5,或7是真的 - 它總是"。 這在邏輯上不是我們想要的! 要進(jìn)行這項(xiàng)工作,你必須在每個(gè)OR運(yùn)算符的每一側(cè)指定一個(gè)完整的測(cè)試:

if (x === 5 || x === 7 || x === 10 ||x === 20) {
  // run my code
}

switch語(yǔ)句

if ... else 語(yǔ)句完成啟用條件代碼的工作,但他們不是沒有他們的缺點(diǎn)。 它們主要適用于您有幾個(gè)選擇的情況,每個(gè)都需要合理數(shù)量的代碼運(yùn)行,和/或條件復(fù)雜(例如多個(gè)邏輯運(yùn)算符)。 對(duì)于只想根據(jù)條件設(shè)置變量為某個(gè)值或打印特定語(yǔ)句的情況,語(yǔ)法可能有點(diǎn)繁瑣,尤其是如果您有大量選擇。

switch 語(yǔ)句是您的朋友, 它們將單個(gè)表達(dá)式/值作為輸入,然后查看多個(gè)選項(xiàng),直到找到與該值匹配的值,并執(zhí)行相應(yīng)的代碼。 這里有一些偽代碼,給你一個(gè)想法:

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
}

這里我們有:

  1. The keyword switch, followed by a set of parentheses.
  2. An expression or value inside the parentheses.
  3. The keyword case, followed by a choice that the expression/value could be, followed by a colon.
  4. Some code to run if the choice matches the expression.
  5. A 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.
  6. As many other cases (bullets 3–5) as you like.
  7. The keyword 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ī)會(huì)等于未知值,您可以安全地忽略該部分。 如果有機(jī)會(huì),但是,你需要包括它來(lái)處理未知的情況。

一個(gè)開關(guān)示例

讓我們看一個(gè)真實(shí)的例子 - 我們將重寫我們的天氣預(yù)報(bào)應(yīng)用程序,使用switch語(yǔ)句:

<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上找到此示例(請(qǐng)參閱 ">運(yùn)行l(wèi)ive 也有)。

三元運(yùn)算符

在我們讓你玩一些例子之前,有一個(gè)最后一點(diǎn)語(yǔ)法我們想介紹給你。 三元或條件運(yùn)算符是一小部分語(yǔ)法,用于測(cè)試 條件并返回一個(gè)值/表達(dá)式,如果它是 true ,另一個(gè)如果是 false - 這在某些情況下可能是有用的,并且可以占用少得多的代碼比 如果你只需要通過(guò) true / false 條件選擇兩個(gè)選項(xiàng),那么 if ... else 偽代碼如下所示:

( condition ) ? run this code : run this code instead

讓我們來(lái)看一個(gè)簡(jiǎn)單的例子:

var greeting = ( isBirthday ) ? 'Happy birthday Mrs. Smith — we hope you have a great day!' : 'Good morning Mrs. Smith.';

這里我們有一個(gè)變量 Birthday - 如果這是 true ,我們給客人一個(gè)生日快樂消息; 如果沒有,我們給她標(biāo)準(zhǔn)的每日問(wèn)候。

三元運(yùn)算符示例

你不必只用三元運(yùn)算符設(shè)置變量值; 你也可以運(yùn)行函數(shù),或代碼行 - 任何你喜歡的。 以下實(shí)例顯示了一個(gè)簡(jiǎn)單的主題選擇器,其中使用三元運(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');
}

這里有一個(gè) < select> >元素來(lái)選擇主題(黑色或白色),以及一個(gè)簡(jiǎn)單的 < h1> 以顯示網(wǎng)站標(biāo)題。 我們還有一個(gè)稱為 update()的函數(shù),它使用兩種顏色作為參數(shù)(輸入)。 網(wǎng)站的背景顏色設(shè)置為第一個(gè)提供的顏色,其文本顏色設(shè)置為第二個(gè)提供的顏色。

最后,我們還有一個(gè) onchange 事件偵聽器,用于運(yùn)行 函數(shù)包含三元運(yùn)算符。 它從測(cè)試條件開始 - select.value ===\'black\'。 如果這返回 true ,我們運(yùn)行帶有黑色和白色參數(shù)的 update()函數(shù),這意味著我們以黑色的背景顏色和白色的文本顏色結(jié)束。 如果它返回 false ,我們運(yùn)行 update()函數(shù),參數(shù)為白色和黑色,這意味著網(wǎng)站顏色被反轉(zhuǎn)。

注意:您也可以 external">在GitHub上找到此示例(請(qǐng)參閱 ">運(yùn)行l(wèi)ive 也有)。

主動(dòng)學(xué)習(xí):一個(gè)簡(jiǎn)單的日歷

在這個(gè)例子中,你將幫助我們完成一個(gè)簡(jiǎn)單的日歷應(yīng)用程序。 在代碼中,你有:

  • A <select> element to allow the user to choose between different months.
  • An onchange event handler to detect when the value selected in the <select> menu is changed.
  • A function called createCalendar() that draws the calendar and displays the correct month in the <h1> element.

我們需要你在 onchange 處理函數(shù)中寫一個(gè)條件語(yǔ)句,就在 // ADD CONDITIONAL HERE 下面。 這應(yīng)該:

  1. Look at the selected month (stored in the choice variable. This will be the <select> element value after the value changes, so "January" for example.)
  2. Set a variable called 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.

提示:

  • You are advised to use logical OR to group multiple months together into a single condition; many of them share the same number of days.
  • Think about which number of days is the most common, and use that as a default value.

如果出錯(cuò),您可以隨時(shí)使用"重置"按鈕重置示例。 如果你真的卡住,按"顯示解決方案"看到一個(gè)解決方案。

主動(dòng)學(xué)習(xí):更多顏色選擇!

在這個(gè)例子中,你將使用我們前面看到的三元運(yùn)算符示例,并將三元運(yùn)算符轉(zhuǎn)換為switch語(yǔ)句,這將允許我們對(duì)簡(jiǎn)單網(wǎng)站應(yīng)用更多的選擇。 查看 < select> - 這 時(shí)間,你會(huì)看到它沒有兩個(gè)主題選項(xiàng),但五。 您需要在 // ADD SWITCH STATEMENT 注釋下面添加一個(gè)switch語(yǔ)句:

  • It should accept the choice variable as its input expression.
  • For each case, the choice should equal one of the possible values that can be selected, i.e. white, black, purple, yellow, or psychedelic.
  • For each case, the 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.

如果出錯(cuò),您可以隨時(shí)使用"重置"按鈕重置示例。 如果你真的卡住,按"顯示解決方案"看到一個(gè)解決方案。

結(jié)論

這就是你真正需要知道的JavaScript中的條件結(jié)構(gòu)現(xiàn)在! 我相信你會(huì)理解這些概念,輕松地完成這些例子; 如果您有任何不明白的地方,請(qǐng)隨時(shí)閱讀本文,或與我們聯(lián)系以尋求幫助。

也可以看看

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)