JavaScript: Control Statements, Part 2JavaScript: جمل التحكم، الجزء الثاني

الشريحة 1 من 14

مقدمة الفصل

ماذا ستتعلم في هذا الفصل

  1. Learn the essentials of counter-controlled repetition.
  2. Use the for and do…while repetition statements to execute statements in a program repeatedly.
  3. Perform multiple selection using the switch selection statement.
  4. Use the break and continue program-control statements.
  5. Use the logical operators to make decisions.
تفاصيل المصدرالفصل 9 · الشريحة ⁦3⁩
المصدر
الفصل 9 · الشريحة ⁦3⁩

Essentials of counter-controlled repetitionأساسيات التكرار بعداد

  1. 1Name of a control variable
  2. 2Initial value of the control variable
  3. 3Increment (or decrement)by which the control variable is modified each time through the loop
  4. 4Condition that tests for the final valueto determine whether looping should continue

من الشرائح

  • Fig. 8.1 (slide 7): var counter = 1; // initialization — while ( counter <= 7 ) // repetition condition — ++counter; // increment.
  • The double-quote character delimits a string literal; inside a string, write it as the escape sequence \".
  • HTML5 allows single (') or double (") quotes around an attribute value; JavaScript allows single quotes inside a string literal.

Which of the following is NOT one of the requirements of counter-controlled repetition?

تفاصيل المصدرالفصل 9 · الشرائح ⁦5–7⁩
المصدر
الفصل 9 · الشرائح ⁦5–7⁩

The for repetition statementجملة for

for statement
Specifies each of the items needed for counter-controlled repetition with a control variable. Its header contains three expressions: initialization; condition; increment expression.

من الشرائح

  • Fig. 8.2 (slide 9): for ( var counter = 1; counter <= 7; ++counter ) — initialization, repetition condition and incrementing are all included in the for statement header.
  • The increment expression acts like a stand-alone statement at the end of the body.
  • Place only expressions involving the control variable in the initialization and increment sections.
  • The three expressions are optional; the two semicolons are required; the portions can contain arithmetic expressions.

In for ( var counter = 1; counter <= 7; ++counter ), what is ++counter?

تفاصيل المصدرالفصل 9 · الشرائح ⁦8–10⁩
المصدر
الفصل 9 · الشرائح ⁦8–10⁩

for: pitfalls and rulesقواعد for وأخطاؤها

The for repetition statement

Off-by-one errorخطأ الفرق بواحد
Can result if the loop's condition uses a < or > instead of a <= or >=, or vice-versa.
Scopeالنطاق
The part of a script in which a variable name can be used.
Decrementالنقصان
A negative "increment": the loop actually counts downward.
  • If the loop-continuation condition initially is false, the body is not performed; execution proceeds with the statement following the for.

A loop must run for counter = 1 to 10 inclusive, but it is written for ( var counter = 1; counter < 10; ++counter ). What kind of error is this?

تفاصيل المصدرالفصل 9 · الشرائح ⁦8, 11⁩
المصدر
الفصل 9 · الشرائح ⁦8, 11⁩

Examples using the for statementأمثلة for

المسألة

Fig. 8.5: sum the even integers from 2 to 100.

  • JavaScript does not include an exponentiation operator: Math.pow(x, y) calculates x raised to the y th power (slide 17).
  • Fig. 8.6 (compound interest, slides 14–16): principal = 1000.00, rate = 0.05; for ( var year = 1; year <= 10; ++year ) amount = principal * Math.pow( 1.0 + rate, year ); each amount is written with amount.toFixed(2), one table row per year.

How does a JavaScript script calculate 1.05 raised to the 3rd power?

تفاصيل المصدرالفصل 9 · الشرائح ⁦12–17⁩
المصدر
الفصل 9 · الشرائح ⁦12–17⁩

switch multiple-selection statementجملة switch

switch
Tests a variable or expression separately for each of the values it may assume; different actions are taken for each value. Consists of a series of case labels and an optional default case.

When control reaches a switch (slide 19)

  1. 1

    The script evaluates the controlling expression in the parentheses.

  2. 2

    Compares this value with the value in each of the case labels.

  3. 3

    If the comparison evaluates to true, the statements after the case label are executed in order until a break statement is reached.

  4. 4

    If no other case is satisfied, the default case runs (usually the last case).

When a case label of a switch matches, how long do the statements after it keep executing?

تفاصيل المصدرالفصل 9 · الشرائح ⁦18–19⁩
المصدر
الفصل 9 · الشرائح ⁦18–19⁩

switch rules and the list exampleقواعد switch ومثال القوائم

switch multiple-selection statement

  • Each case can have multiple actions; braces are not required around them.
  • break is not required for the last case: control automatically continues with the next statement after the switch.
  • Several case labels listed together (e.g., case 1: case 2:) execute the same set of actions for each case.

من الشرائح

  • Fig. 8.7 (slides 21–22): choice = window.prompt( "Select a list style: 1 (numbered), 2 (lettered), 3 (roman numbered)", "1" ); case "1": <ol> "Numbered List"; case "2": list-style-type: upper-alpha "Lettered List"; case "3": list-style-type: upper-roman "Roman Numbered List"; default: validInput = false.

CSS list-style-type values (slide 18)

  • decimal (default)
  • lower-roman
  • upper-roman
  • lower-alpha
  • upper-alpha
تفاصيل المصدرالفصل 9 · الشرائح ⁦18, 20, 21, 22⁩
المصدر
الفصل 9 · الشرائح ⁦18, 20, 21, 22⁩

do…while repetition statementجملة do…while

do…while
Tests the loop-continuation condition after the loop body executes — the loop body always executes at least once.

من الشرائح

  • Fig. 8.9 (slide 28): var counter = 1; do { … writes an h1 … h6 heading … ++counter; } while ( counter <= 6 );

var n = 10; do { document.writeln( n ); ++n; } while ( n < 5 ); How many times is n written?

تفاصيل المصدرالفصل 9 · الشرائح ⁦27–28⁩
المصدر
الفصل 9 · الشرائح ⁦27–28⁩

break and continuebreak و continue

break

  • In while, for, do…while or switch
  • Immediate exit from the statement
  • Execution continues with the next statement in sequence
  • Uses: escape early from a loop; skip the remainder of a switch

continue

  • In while, for or do…while
  • Skips the remaining statements in the body
  • Proceeds with the next iteration
  • while / do…while: the test evaluates immediately; for: the increment expression executes, then the test

for ( var count = 1; count <= 10; ++count ) { if ( count == 5 ) break; document.writeln( count + " " ); } Which values does the loop write?

تفاصيل المصدرالفصل 9 · الشرائح ⁦29–30⁩
المصدر
الفصل 9 · الشرائح ⁦29–30⁩

سؤال سريع

break and continue statements

for ( var count = 1; count <= 10; ++count ) { if ( count == 5 ) continue; document.writeln( count + " " ); } Which values does the loop write?

تفاصيل المصدرالفصل 9 · الشريحة ⁦33⁩
المصدر
الفصل 9 · الشريحة ⁦33⁩

Logical operatorsالعوامل المنطقية

&& (logical AND)
Ensures that two conditions are both true before choosing a certain path of execution.
|| (logical OR)
Ensures that either or both of two conditions are true before choosing a certain path of execution.
! (logical NOT, logical negation)
Reverses the meaning of a condition; has only a single condition as an operand (a unary operator).
Truth tables for && and || (Figs. 8.13–8.14)
expression1expression2expression1 && expression2expression1 || expression2
falsefalsefalsefalse
falsetruefalsetrue
truefalsefalsetrue
truetruetruetrue
  • Fig. 8.15: !false is true; !true is false.
  • JavaScript evaluates to false or true all expressions that include relational, equality and/or logical operators.

What is false && true?

تفاصيل المصدرالفصل 9 · الشرائح ⁦35, 36, 37, 39⁩
المصدر
الفصل 9 · الشرائح ⁦35, 36, 37, 39⁩

Precedence and short-circuit evaluationالأسبقية والتقييم المختصر

Logical operators

  • && has a higher precedence than ||. Both associate from left to right.
  • An expression containing && or || is evaluated only until truth or falsity is known: short-circuit evaluation.
Fig. 8.16: precedence and associativity of the operators discussed so far (highest first)
OperatorAssociativityType
++ -- !right to leftunary
* / %left to rightmultiplicative
+ -left to rightadditive
< <= > >=left to rightrelational
== != === !==left to rightequality
&&left to rightlogical AND
||left to rightlogical OR
?:right to leftconditional
= += -= *= /= %=right to leftassignment

Evaluate true || false && false.

تفاصيل المصدرالفصل 9 · الشرائح ⁦38, 41⁩
المصدر
الفصل 9 · الشرائح ⁦38, 41⁩

Nonboolean values as true or falseالقيم كصحيح أو خطأ

Logical operators

Considered true

  • Nonzero numeric values
  • Any string that contains characters
  • All objects

Considered false

  • The numeric value zero
  • The empty string
  • The value null
  • Variables that have been declared but not initialized

Which value is considered true when converted to a boolean?

تفاصيل المصدرالفصل 9 · الشريحة ⁦40⁩
المصدر
الفصل 9 · الشريحة ⁦40⁩

الخلاصة

تفاصيل المصدر
المصدر
الفصل 9

خريطة الفصل