HTML and CSS Reference
In-Depth Information
Using Logical Operators
JavaScript also supports logical operators that allow you to connect several expressions.
Figure 11-30 lists the logical operators supported by JavaScript. The logical operator &&
returns a value of true only if both of the expressions are true. For example, the statement
(x < 100) && (y == 100)
is true only if x is less than 100 and y is equal to 100.
Figure 11-30
logical operators
Operator
Definition Expression
Description
&&
and
(x == 20) && (y == 25) Returns true if x equals 20 and y equals 25
||
or
(x == 20) || (y < 10) Returns true if x equals 20 or y is less than 10
!
not
!(x == 20)
Returns true if x does not equal 20
You'll use conditional, comparison, and logical operators to write code for the three
rules described above to convert 24-hour time to 12-hour time. First, you need a variable
named ampm that indicates whether the time is a.m. or p.m. Recall that the value of the
current hour is stored in the thisHour variable. If the value of the thisHour variable is
less than 12, the text of the ampm variable is a.m. ; otherwise, its text is p.m. The condi-
tional operator for this rule is as follows:
var ampm = (thisHour < 12) ? “ a.m.” : “ p.m.”;
The second rule should check whether the thisHour value is greater than 12. If so, the
rule should subtract 12 from the thisHour value; otherwise, it should leave the value
unchanged. You'll do this using the following conditional operator:
thisHour = (thisHour > 12) ? thisHour - 12 : thisHour;
The third rule should check whether thisHour is equal to 0. If so, the rule should
change the value of thisHour to 12; otherwise, it should leave the value unchanged.
The code for this rule is as follows:
thisHour = (thisHour == 0) ? 12 : thisHour;
You'll add these commands to the showTime() function in the functions.js file.
To modify the showTime() function:
2. Within the showTime() function, below the statement that creates the thisHour
variable, insert the following commands:
// change thisHour from 24-hour time to 12-hour time by:
// 1) if thisHour < 12 then set ampm to “ a.m.” otherwise set it to
“ p.m.”
var ampm = (thisHour < 12) ? “ a.m.” : “ p.m.”;
// 2) if thisHour > 12 then subtract 12 from the thisHour variable
thisHour = (thisHour > 12) ? thisHour - 12 : thisHour;
// 3) if thisHour equals 0, change it to 12
thisHour = (thisHour == 0) ? 12 : thisHour;

Search WWH ::

Custom Search