Tải bản đầy đủ - 0 (trang)
Chapter 6. JavaScript: Control Statements II

Chapter 6. JavaScript: Control Statements II

Tải bản đầy đủ - 0trang

thefinalissue.

—Demosthenes

Outline

6.1 Introduction

6.2 EssentialsofCounter-ControlledRepetition

6.3 forRepetitionStatement

6.4 ExamplesUsingtheforStatement

6.5 switchMultiple-SelectionStatement

6.6 do...whileRepetitionStatement

6.7 breakandcontinueStatements

6.8 LabeledbreakandcontinueStatements

6.9 LogicalOperators

6.10 WebResources



6.1.Introduction

Chapter5beganourintroductiontothetypesofbuildingblocks

thatareavailableforproblemsolvingandusedthemtoemploy

provenprogram-constructionprinciples.Inthischapter,we

introduceJavaScript'sremainingcontrolstatements(withthe

exceptionoffor...in,whichispresentedinChapter8).Asin

Chapter5,theJavaScripttechniquesyouwilllearnhereare

applicabletomosthigh-levellanguages.Inlaterchapters,you'll

seethatcontrolstructuresarehelpfulinmanipulatingobjects.



6.JavaScript:ControlStatementsII

Objectives

Inthischapteryouwilllearn:

Theessentialsofcounter-controlledrepetition

Tousetheforanddo...whilerepetitionstatementsto

executestatementsinaprogramrepeatedly.

Toperformmultipleselectionusingtheswitchselection

statement.

Tousethebreakandcontinueprogram-control

statements

Tousethelogicaloperators.

Noteverythingthatcanbecountedcounts,andnot

everythingthatcountscanbecounted.

—AlbertEinstein

Whocancontrolhisfate?

—WilliamShakespeare

Theusedkeyisalwaysbright.

—BenjaminFranklin

Intelligence...isthefacultyofmakingartificial

objects,especiallytoolstomaketools.

—HenriBergson

Everyadvantageinthepastisjudgedinthelightof



thefinalissue.

—Demosthenes

Outline

6.1 Introduction

6.2 EssentialsofCounter-ControlledRepetition

6.3 forRepetitionStatement

6.4 ExamplesUsingtheforStatement

6.5 switchMultiple-SelectionStatement

6.6 do...whileRepetitionStatement

6.7 breakandcontinueStatements

6.8 LabeledbreakandcontinueStatements

6.9 LogicalOperators

6.10 WebResources



6.1.Introduction

Chapter5beganourintroductiontothetypesofbuildingblocks

thatareavailableforproblemsolvingandusedthemtoemploy

provenprogram-constructionprinciples.Inthischapter,we

introduceJavaScript'sremainingcontrolstatements(withthe

exceptionoffor...in,whichispresentedinChapter8).Asin

Chapter5,theJavaScripttechniquesyouwilllearnhereare

applicabletomosthigh-levellanguages.Inlaterchapters,you'll

seethatcontrolstructuresarehelpfulinmanipulatingobjects.



6.2.EssentialsofCounter-Controlled

Repetition

Counter-controlledrepetitionrequires:

1. Thenameofacontrolvariable(orloopcounter).

2. Theinitialvalueofthecontrolvariable.

3. Theincrement(ordecrement)bywhichthecontrolvariable

ismodifiedeachtimethroughtheloop(alsoknownaseach

iterationoftheloop).

4. Theconditionthattestsforthefinalvalueofthecontrol

variabletodeterminewhetherloopingshouldcontinue.

Toseethefourelementsofcounter-controlledrepetition,

considerthesimplescriptshowninFig.6.1,whichdisplayslines

ofXHTMLtextthatillustratethesevendifferentfontsizes

supportedbyXHTML.Thedeclarationinline12namesthe

controlvariable(counter),reservesspaceforitinmemoryand

setsittoaninitialvalueof1.Thedeclarationandinitialization

ofcountercouldalsohavebeenaccomplishedbythefollowing

declarationandassignmentstatement:

varcounter;//declarecounter

counter=1;//initializecounterto1

Figure6.1.Counter-controlledrepetition.

CodeView:

1

2
3"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"

4

5

6



7

8

9Counter-ControlledRepetition

10

11
13

14while(counter<=7)//repetitioncondition

15{

16document.writeln("
17counter+"ex\">XHTMLfontsize"+counter

18"ex

");

19++counter;//increment

20}//endwhile

21//-->

22

23

24









[Viewfullsizeimage]



















Lines16–18inthewhilestatementwriteaparagraphelement

consistingofthestring"XHTMLfontsize"concatenatedwith

thecontrolvariablecounter'svalue,whichrepresentsthefont

size.AninlineCSSstyleattributesetsthefont-sizeproperty

tothevalueofcounterconcatenatedtoex.Notetheuseofthe

escapesequence\",whichisplacedaroundattributestyle's

value.Becausethedouble-quotecharacterdelimitsthe

beginningandendofastringliteralinJavaScript,itcannotbe

usedinthecontentsofthestringunlessitisprecededbya\to

createtheescapesequence\".Forexample,ifcounteris5,

theprecedingstatementproducesthemarkup

XHTMLfontsize5ex





XHTMLallowseithersinglequotes(')ordoublequotes(")to



beplacedaroundthevaluespecifiedforanattribute.JavaScript

allowssinglequotestobeplacedinastringliteral.Thus,we

couldhaveplacedsinglequotesaroundthefont-sizeproperty

toproduceequivalentXHTMLoutputwithouttheuseofescape

sequences.

CommonProgrammingError6.1

Placingadouble-quote(")characterinside

astringliteralthatisdelimitedbydouble

quotescausesaruntimeerrorwhenthe

scriptisinterpreted.Tobedisplayedas

partofastringliteral,adouble-quote(")

charactermustbeprecededbya\toform

theescapesequence\".



Line19inthewhilestatementincrementsthecontrolvariable

by1foreachiterationoftheloop(i.e.,eachtimethebodyof

theloopisperformed).Theloop-continuationcondition(line14)

inthewhilestatementtestswhetherthevalueofthecontrol

variableislessthanorequalto7(thefinalvalueforwhichthe

conditionistrue).Notethatthebodyofthiswhilestatement

executesevenwhenthecontrolvariableis7.Theloop

terminateswhenthecontrolvariableexceeds7(i.e.,counter

becomes8).

GoodProgrammingPractice6.1

Indentthestatementsinthebodyofeach

controlstructure.



GoodProgrammingPractice6.2

Putablanklinebeforeandaftereach

controlstructure,tomakeitstandoutin

theprogram.



GoodProgrammingPractice6.3

Toomanylevelsofnestingcanmakea

programdifficulttounderstand.Asa

generalrule,trytoavoidusingmorethan

threelevelsofnesting.



GoodProgrammingPractice6.4

Verticalspacingaboveandbelowcontrol

structuresandindentationofthebodiesof

controlstructuresintheheadersofthe

controlstructuregiveprogramsatwodimensionalappearancethatenhances

readability.



6.3.forRepetitionStatement

Theforrepetitionstatementhandlesallthedetailsof

counter-controlledrepetition.Figure6.2illustratesthepowerof

theforstatementbyreimplementingthescriptofFig.6.1.

Figure6.2.Counter-controlledrepetitionwiththefor

statement.

CodeView:



1

2
3"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"

4

5

6

20

21

22









[Viewfullsizeimage]



















Whentheforstatementbeginsexecuting(line15),thecontrol

variablecounterisdeclaredandisinitializedto1(i.e.,thefirst

statementoftheforstatementdeclaresthecontrolvariable's

nameandprovidesthecontrolvariable'sinitialvalue).Next,the

loop-continuationcondition,counter<=7,ischecked.The

conditioncontainsthefinalvalue(7)ofthecontrolvariable.The

initialvalueofcounteris1.Therefore,theconditionissatisfied

(i.e.,true),sothebodystatement(lines16–18)writesa

paragraphelementintheXHTMLdocument.Then,variable

counterisincrementedintheexpression++counterandthe

loopcontinuesexecutionwiththeloop-continuationtest.The

controlvariableisnowequalto2,sothefinalvalueisnot

exceededandtheprogramperformsthebodystatementagain

(i.e.,performsthenextiterationoftheloop).Thisprocess

continuesuntilthecontrolvariablecounterbecomes8,at

whichpointtheloop-continuationtestfailsandtherepetition



terminates.

Theprogramcontinuesbyperformingthefirststatementafter

theforstatement.(Inthiscase,thescriptterminates,because

theinterpreterreachestheendofthescript.)

Figure6.3takesacloserlookattheforstatementatline15of

Fig.6.2.Theforstatement'sfirstline(includingthekeyword

forandeverythinginparenthesesafterfor)isoftencalledthe

forstatementheader.Notethattheforstatement"doesit

all"—itspecifieseachoftheitemsneededforcounter-controlled

repetitionwithacontrolvariable.

Figure6.3.forstatementheadercomponents.



NotethatFig.6.3usestheloop-continuationconditioncounter

<=7.Ifyouincorrectlywritecounter<7,theloopwill

executeonlysixtimes.Thisisanexampleofthecommonlogic

errorcalledanoff-by-oneerror.

CommonProgrammingError6.2

Usinganincorrectrelationaloperatororan

incorrectfinalvalueofaloopcounterinthe

conditionofawhile,forordo...while

statementcancauseanoff-by-oneerroror

aninfiniteloop.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 6. JavaScript: Control Statements II

Tải bản đầy đủ ngay(0 tr)

×