Making decisions in your code — conditionals
先决条件: | 基本的计算机素养,对HTML和CSS的基本了解, JavaScript第一步。 |
---|---|
目的: | 了解如何在JavaScript中使用条件结构。 |
你可以有一个条件..!
人类(和其他动物)在影响他们生活的所有时间做决定,从小("我应该吃一个饼干还是两个?")到大("我应该留在我的祖国,在我父亲的农场工作, 我应该搬到美国,研究天体物理学吗?")
条件语句允许我们在JavaScript中表示这样的决策,从必须做出的选择(例如"一个或两个")到所得到的结果或那些选择(或许"吃一个cookie"的结果可能是"仍然 感觉饥饿","吃两个饼干"的结果可能"感觉充满了,但妈妈骂我吃所有的饼干"。)
if ... else语句
让我们来看看你将在JavaScript中使用的最常见类型的条件语句 - 谦逊 /Statements/if...else\">if ... else
语句/ if ... else">语句。
基本if ... else语法
基本 if ... else
语法如下所示: pseudocode :
if (condition) { code to run if condition is true } else { run some other code instead }
这里我们有:
- The keyword
if
followed by some parentheses. - 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
orfalse
. - 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
. - The keyword
else
. - 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
.
此代码是非常易读的 - 它是说"如果 条件返回 true
,运行代码A, >运行代码B"
你应该注意,你不必包括 else
和第二个花括号块 - 以下也是完美的法律代码:
if (condition) { code to run if condition is true } run some other code
但是,你需要在这里小心 - 在这种情况下,第二个代码块不受条件语句控制,所以它将总是运行,无论条件是否返回 true / code>或
false
。 这不一定是坏事,但它可能不是你想要的 - 通常你会想运行一个代码块或另一个,而不是两者。
作为最后一点,有时可能会看到 if ... else
语句写入没有花括号,以下面的缩写样式:
if (condition) code to run if condition is true else run some other code instead
这是完全有效的代码,但是不推荐使用它 - 更容易阅读代码,并解决发生了什么,如果你使用花括号来分隔代码块,并使用多行和缩进。
一个真正的例子
为了更好地理解这个语法,让我们考虑一个真实的例子。 想象一个孩子被他们的母亲或父亲请求帮忙做家务。 父母可能会说"嗨甜心,如果你帮助我去购物,我会给你一些额外的津贴,所以你可以买得起你想要的玩具。 在JavaScript中,我们可以这样表示:
var shoppingDone = false; if (shoppingDone === true) { var childsAllowance = 10; } else { var childsAllowance = 5; }
如图所示的代码总是导致 shoppingDone
变量返回 false
,这意味着我们可怜的孩子会失望。 如果孩子做了购物,那么应该由我们提供一个机制让父母将 shoppingDone
变量设置为 true
。
注意:您可以查看更多 ="external">此示例的完整版本在GitHub (也看到它 running live 。)
否则if
最后一个例子为我们提供了两个选择或结果 - 但是如果我们想要两个以上呢?
有一种方法可以将额外的选择/结果链接到你的 if ... else
- 使用 else if
。 每个额外的选择需要一个额外的块放在 if(){...}
和 else {...}
之间 - 检查下面更多涉及的例子, 可以是简单的天气预报应用程序的一部分:
<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 = ''; } }
- Here we've got an HTML
<select>
element allowing us to make different weather choices, and a simple paragraph. - 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, thesetWeather()
function is run. - 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 ofchoice
is. Notice how all the conditions are tested inelse if() {...}
blocks, except for the first one, which is tested in anif() {...} block
. - 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 aretrue
. 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上找到此示例( "外部">看到它运行实时也有)。
关于比较运算符的注释
比较运算符用于测试条件语句中的条件。 我们首先查看了 JavaScript - 数字和运算符的基本数学文章中的比较运算符。 我们的选择是:
-
===
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
)值,以及一个常见的模式,你会反复遇到。 任何不是 false
, undefined
, null
, 0
, NaN
或者测试为条件语句时,空字符串(\'\'
)实际返回 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.'); }
并且,回到我们以前的例子,关于孩子为他们的父母做杂事,你可以这样写:
var shoppingDone = false; if (shoppingDone) { // don't need to explicitly specify '=== true' var childsAllowance = 10; } else { var childsAllowance = 5; }
嵌套if ... else
将一个如果... else
语句放在另一个 - 中来嵌套它是完全正确的。 例如,我们可以更新我们的天气预报应用程序,根据温度是什么显示更多的选择:
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
语句完全独立于另一个工作。
逻辑运算符:AND,OR和NOT
如果要测试多个条件而不编写嵌套的 if ... else
语句, / Operators / Logical_Operators">逻辑运算符可以帮助您。 当在条件下使用时,前两个操作如下:
-
&&
— AND; allows you to chain together two or more expressions so that all of them have to individually evaluate totrue
for the whole expression to returntrue
. -
||
— OR; allows you to chain together two or more expressions so that one or more of them have to individually evaluate totrue
for the whole expression to returntrue
.
为了给你一个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.'); }
由!
运算符表示的最后一种类型的逻辑运算符NOT可用于否定表达式。 让我们在上面的例子中结合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运算符将否定它,以便整个表达式返回 false
。
您可以在任何结构中将任意数量的逻辑语句组合在一起。 以下示例仅在两个OR语句都返回true的情况下执行代码,这意味着总体AND语句将返回true:
if ((x === 5 || y > 3 || z <= 10) && (loggedIn || userName === 'Steve')) { // run the code }
在条件语句中使用逻辑OR运算符时常见的错误是尝试说明其值要被检查一次的变量,然后给出一个值列表,它可以返回true,由 ||
>(OR)运算符。 例如:
if (x === 5 || 7 || 10 || 20) { // run my code }
在这种情况下, if(...)
中的条件将始终评估为true,因为7(或任何其他非零值)总是评估为true。 这个条件实际上是说"如果x等于5,或7是真的 - 它总是"。 这在逻辑上不是我们想要的! 要进行这项工作,你必须在每个OR运算符的每一侧指定一个完整的测试:
if (x === 5 || x === 7 || x === 10 ||x === 20) { // run my code }
switch语句
if ... else
语句完成启用条件代码的工作,但他们不是没有他们的缺点。 它们主要适用于您有几个选择的情况,每个都需要合理数量的代码运行,和/或条件复杂(例如多个逻辑运算符)。 对于只想根据条件设置变量为某个值或打印特定语句的情况,语法可能有点繁琐,尤其是如果您有大量选择。
switch
语句是您的朋友, 它们将单个表达式/值作为输入,然后查看多个选项,直到找到与该值匹配的值,并执行相应的代码。 这里有一些伪代码,给你一个想法:
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 }
这里我们有:
- The keyword
switch
, followed by a set of parentheses. - An expression or value inside the parentheses.
- The keyword
case
, followed by a choice that the expression/value could be, followed by a colon. - Some code to run if the choice matches the expression.
- 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. - As many other cases (bullets 3–5) as you like.
- The keyword
default
, followed by exactly the same code pattern as one of the cases (bullets 3–5), except thatdefault
does not have a choice after it, and you don't need tobreak
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.
注意:您不必包含默认
部分 - 如果表达式没有机会等于未知值,您可以安全地忽略该部分。 如果有机会,但是,你需要包括它来处理未知的情况。
一个开关示例
让我们看一个真实的例子 - 我们将重写我们的天气预报应用程序,使用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上找到此示例(请参阅 ">运行live 也有)。
三元运算符
在我们让你玩一些例子之前,有一个最后一点语法我们想介绍给你。 三元或条件运算符是一小部分语法,用于测试 条件并返回一个值/表达式,如果它是 true
,另一个如果是 false
- 这在某些情况下可能是有用的,并且可以占用少得多的代码比 如果你只需要通过 true
/ false
条件选择两个选项,那么 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
,我们给客人一个生日快乐消息; 如果没有,我们给她标准的每日问候。
三元运算符示例
你不必只用三元运算符设置变量值; 你也可以运行函数,或代码行 - 任何你喜欢的。 以下实例显示了一个简单的主题选择器,其中使用三元运算符应用网站的样式。
<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> 以显示网站标题。 我们还有一个称为 update()
的函数,它使用两种颜色作为参数(输入)。 网站的背景颜色设置为第一个提供的颜色,其文本颜色设置为第二个提供的颜色。
最后,我们还有一个 onchange 事件侦听器,用于运行 函数包含三元运算符。 它从测试条件开始 - select.value ===\'black\'
。 如果这返回 true
,我们运行带有黑色和白色参数的 update()
函数,这意味着我们以黑色的背景颜色和白色的文本颜色结束。 如果它返回 false
,我们运行 update()
函数,参数为白色和黑色,这意味着网站颜色被反转。
注意:您也可以 external">在GitHub上找到此示例(请参阅 ">运行live 也有)。
主动学习:一个简单的日历
在这个例子中,你将帮助我们完成一个简单的日历应用程序。 在代码中,你有:
- 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
处理函数中写一个条件语句,就在 // ADD CONDITIONAL HERE
下面。 这应该:
- 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.) - 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.
如果出错,您可以随时使用"重置"按钮重置示例。 如果你真的卡住,按"显示解决方案"看到一个解决方案。
Playable code
<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);
主动学习:更多颜色选择!
在这个例子中,你将使用我们前面看到的三元运算符示例,并将三元运算符转换为switch语句,这将允许我们对简单网站应用更多的选择。 查看 < select>
- 这 时间,你会看到它没有两个主题选项,但五。 您需要在 // ADD SWITCH STATEMENT
注释下面添加一个switch语句:
- 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.
如果出错,您可以随时使用"重置"按钮重置示例。 如果你真的卡住,按"显示解决方案"看到一个解决方案。
Playable code 2
<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中的条件结构现在! 我相信你会理解这些概念,轻松地完成这些例子; 如果您有任何不明白的地方,请随时阅读本文,或与我们联系以寻求帮助。