property name is th at access to array e le ments is mostly significantly faster than access
to regular object properties. That’s due to the fact that Java Script impleme ntations
typically op timize array s fo r index access.
The second dierence is that when you use a numeric index to add a new elem ent, the
length property of an array is automatically updated for you.
Maria: You said before that array s were dynamic in the sense that you could add or
remove elements. You showed us that an element is added automatically by simply
giving a value to a non-existent element. But how do you remove elements?
Professor: One way of doing that is to explicitly change the value of the length
property, which will automatically truncate or grow the size of the arra y. If you make
length smaller, then you eectively delete e le ments from the end of an array.
There also exist certain array methods like, for example, pop() and push(), which
you can use to explicitly ad d or remove ele ments.
I will now show you the for loop, which is commonly used in connection with a rrays.
9.3 for Loop
Professor: The for statement is a looping instrument similar to the while loop but
it is often more convenient when the code has to do with counting of some kind.
Counting consists of three elementary tasks: first, setting a counter to an initial value,
second, deciding when to stop, and third, deciding upon the size of the increment
(or d ecrement f or countdown). A variable used as a c ounter in a for loop is first
initialized and then tested before each iteration of the loop is executed. At th e end
of each iteration the co unter is increm ented or other w ise updated. All thr ee central
operations upon a counting variable, the initialization, the test, and the update, are
neatly grouped inside the parentheses at the beginning of the fo r loop. This is the
loop’s syntax:
for (initialize ; test ; update ) do_something
The expr essions initialize , test , and update are responsib le for manipulating a
counter variable, and do_something is a statement that represents the lo op body.
I thought it best to explain how the for loop works in a two-stage example of printing
the 10 times multiplication table. In the first stage we simply fix one of the multipli-
cands to, say, three, and print a single row of the table:
var x = 3, y;
document.write("<table border="1">");
document.write("<tr>");
for (y = 1; y <= 10; y++) {
//Prints numbers 3, 6, 9, 12, ..., 30 in one table row.
document.write("<td>" + x * y + "</td>");
}
9.3. f or Loop 173
document.write("</tr>");
document.write("</table>");
Notice how I used strings of HTM L code as arguments of document.write () to
produce markup dyna mically. The code is of course interpreted by the browser as any
other HTML. Notice also the backslash characters () preceding the quotes around the
value 1 inside the <table> opening ta g. The backslash is a so-called escape char-
acter, which has a special meaning in JavaScript strings. Together with the character
that it precedes it forms an escape sequence, defining a character that you could oth-
erwise not use within a string. For example, when a string literal starts with a double
quote, you cannot use double quotes within that string because the first occurrence of
a double quote ends the string . You c an use the escape sequenc e " instead. Another
example of usin g an escape sequence would be a newline character, which can be
represented as n.
Mike: Is this similar to character entities in HTML?
Professor: It is indee d. But if you don’t like to use escape sequences, you can just as
well use dierent types of q uotes instead, as single quotes inside double quotes:
document.write("<table border=’1’>");
Here is the flowchart of the for loop from the above example.
document.write(
y <= 10
false
true
y = 1
y++
"<td>" + x
*
y + "</td>"
);
174 Meeting 9. Understanding Arrays and Strings
You can see that the initialization of the loop counter, which is the expression y = 1,
is performed right at the beginning of the for loop. It is performed only once because
no path loops back before that expression. Next, the loop test is evaluated, which is the
expression y < = 10. If that expression evaluates to false, then the loop terminates.
Otherwise, the loop b ody is executed, which outputs the start and end tags of a table
cell and prints the value of the expression x * y in b etween. Finally, y is incremented
before g oing back to be tested again, and the story repeats itself.
Although this loop is somehow more complex than the other two loops that we know,
I don’t think it needs any more explanation.
Mike: You said the other day that any rectangular box in a flowchart can be replaced
by an arbitrary statement. Looking at the for loop in the ab ove example, I fin d it hard
to believe that this is really so.
Professor: Youre quite right about that. It’s true that initialize , test , and
update are expressions and not statements. There are always exceptions to the rules,
aren’t there?
In or der to produce the complete multiplication table, we just need to repeat the part
of the code responsible for writing a table row. We can do that by simply putting the
code into yet another for loop, iterating x from one to 10. Like this:
var x, y;
document.write("<table border="1">");
for (x = 1; x <= 10; x++) {
document.write("<tr>");
for (y = 1; y <= 10; y++) {
document.write("<td>" + x * y + "</td>");
}
}
document.write("</tr>");
document.write("</table>");
The time is ripe to finish our lucky lottery number generator. I propose the following
algorithm :
Repeat
six time s:
Repeat
∗∗
Set number to a random value between 1 and 5 4.
If number doesn’t exist in drawnNu mbersList Then
Add number to drawnNumbersList.
Stop repeating
∗∗
.
End If
End Re peat
∗∗
End Repeat
Print the six lucky nu mbers (contents of drawnNumbersList).
9.3. f or Loop 175
I think that we shouldn’t have any diculties implem enting the algorithm excep t for
the part that che cks whether number already exists. This can be done as f ollows:
Set an auxiliary variable exists to false.
Repeat for every element of drawnNumbersList:
If number is the same as the value of the element Then
Set exists to true.
End If
End Repeat
Incidenta lly, the ap proach that I have just taken is called top-down design. Using
this approach you ba sically break down a problem into a c omposition of several less-
complex subproblems. Then you further brea k down these subproblems to even sim-
pler ones until they are simple en ough for you to implement.
Every time the above loop finishes, the variable exists holds th e information about
whether or not number already exists in the drawnNumber sList array. It is not ha rd
to see that this is, in fact, a single for loop containing a single if conditional. The
following a re the necessary ingred ie nts to build the loop:
Initialization: exists = false and i = 0 (i is cho sen to be an index to the
drawnNumbersList array).
Loop test: i < drawnNumbersList.length (the index of th e last element is
one less than the length of the array ).
Update: i++ (g o to the next array element).
Loop’s body: if number is equal to the ith element of drawnNumbersList,
then set exists to true.
Notice that exists is not a counter but I still cho se to initialize it at the same spot as
the loop counter. That’s an obvious thing to do because exists should be initialized
to false every time the loop starts anew, and it is m uch easier to understand wha t the
loop is doing if you keep all the nece ssary loop initialization stu in one place.
We only need to find an appropriate operator to join the two initializations into a single
expression.
Maria: We can use a logical AND operator to do that.
Professor: That won’t work bec ause of short-circuit evaluation. Namely, when two
expressions are jo ined by a logical operator, it can happe n that the value of the expres-
sion that is evaluated first already decid es the final return value of the whole Boolean
expression. In such a case the other expression is short-circuit evaluated. Eectively
that means it is not evaluated at all.
Consider, for example, the following Boolea n expression:
176 Meeting 9. Understanding Arrays and Strings
(i = 0) && (exists = false) //The expression on the right is not
//evaluated.
Because the expression i = 0 retur ns a falsy value, there is no way that the whole
Boolean expression can evaluate to true, no matter what the value of the expression
exists = fals e is. This expression is therefor e never evaluated.
We will use a comm a operator (,) to join both initialization expressions. This is
probably the only situation where you’re going to use this operator, but it’s still good
to know exactly how it works. The comma operator evaluates both of its o perands
(from left to right) and returns the value of its right opera nd. Consider, for example,
the following expression:
i = 0, exists = false //Returns false
Here the variable i is first set to zero and then exists is set to false. The return
value of the whole expression is equal to the return value of the second assignment,
which is false. We’re not going to use this return value, though. The important
thing is that both assignments are joined in a single expression and that both actually
happen.
Mike: How can we stop repeating a loop from within an if statement? I’m talking
about the loop on page 175 marked by two asterisks.
Professor: We can use a br eak statement. You already know that break terminates
a switch stateme nt but you can use it to terminate loops as well. Whenever a break
is encountered within a loop, that loop is terminated and the program execution con-
tinues immediately after the loop that has just terminated.
This is now a completed lucky lottery number generator:
var number, exists;
var drawnNumbersList = [];
var i, n;
for (n = 0; n < 6; n++) {
while (true) { //An infinite loop
number = Math.floor(Math.random() * 54) + 1;
for (exists = false, i = 0; i < drawnNumbersList.length; i++) {
if (number == drawnNumbersList[i]) {
exists = true;
}
}
if (!exists) {
drawnNumbersList[n] = number;
break; //Exits the infinite loop
}
}
}
document.write(drawnNumbersList);
9.3. f or Loop 177
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.221.0