- Object-Oriented JavaScript(Second Edition)
- Stoyan Stefanov Kumar Chetan Sharma
- 392字
- 2021-08-13 16:19:29
Conditions and loops
Conditions provide a simple but powerful way to control the flow of code execution. Loops allow you to perform repetitive operations with less code. Let's take a look at:
if
conditionsswitch
statementswhile
,do-while
,for
, andfor-in
loops
Note
The examples in the following sections require you to switch to the multiline Firebug console. Or, if you use the WebKit console, use Shift + Enter instead of Enter to add a new line.
The if condition
Here's a simple example of an if
condition:
var result = '', a = 3; if (a > 2) { result = 'a is greater than 2'; }
The parts of the if
condition are:
- The
if
statement - A condition in parentheses—"is
a
greater than 2?" - A block of code wrapped in
{}
that executes if the condition is satisfied
The condition (the part in parentheses) always returns a Boolean value, and may also contain the following:
- A logical operation:
!
,&&
, or||
- A comparison, such as
===
,!=
,>
, and so on - Any value or variable that can be converted to a Boolean
- A combination of the above
The else clause
There can also be an optional else
part of the if
condition. The else
statement is followed by a block of code that runs if the condition evaluates to false
:
if (a > 2) { result = 'a is greater than 2'; } else { result = 'a is NOT greater than 2'; }
In between the if
and the else
, there can also be an unlimited number of else if
conditions. Here's an example:
if (a > 2 || a < -2) { result = 'a is not between -2 and 2'; } else if (a === 0 && b === 0) { result = 'both a and b are zeros'; } else if (a === b) { result = 'a and b are equal'; } else { result = 'I give up'; }
You can also nest conditions by putting new conditions within any of the blocks:
if (a === 1) { if (b === 2) { result = 'a is 1 and b is 2'; } else { result = 'a is 1 but b is definitely not 2'; } } else { result = 'a is not 1, no idea about b'; }
- Mastering OpenCV Android Application Programming
- 精通搜索分析
- SQL語(yǔ)言從入門(mén)到精通
- Python數(shù)據(jù)挖掘與機(jī)器學(xué)習(xí)實(shí)戰(zhàn)
- C程序設(shè)計(jì)案例教程
- Java程序設(shè)計(jì)
- GameMaker Essentials
- R語(yǔ)言:邁向大數(shù)據(jù)之路(加強(qiáng)版)
- Ext JS 4 Plugin and Extension Development
- C語(yǔ)言程序設(shè)計(jì)
- Java 7 Concurrency Cookbook
- Backbone.js Patterns and Best Practices
- Android開(kāi)發(fā)進(jìn)階實(shí)戰(zhàn):拓展與提升
- ASP.NET jQuery Cookbook(Second Edition)
- 虛擬現(xiàn)實(shí):引領(lǐng)未來(lái)的人機(jī)交互革命