JavaScript 6 – struttura dei programmi – 4

Continuo da qui a copiare qui.

Cicli while e do
Consider a program that prints all even numbers from 0 to 12. One way to write this is as follows:


lo salvo nel file c0.js e lo eseguo nel terminale, viene meglio

That works, but the idea of writing a program is to make something less work, not more. If we needed all even numbers less than 1,000, the previous would be unworkable. What we need is a way to repeat some code. This form of control flow is called a loop (ciclo):

Looping control flow allows us to go back to some point in the program where we were before and repeat it with our current program state. If we combine this with a variable that counts, we can do something like this (come sopra, lo metto nel file c1.js):

var number = 0;
while (number <= 12) {
  number = number + 2;

A statement starting with the keyword while creates a loop. The word while is followed by an expression in parentheses and then a statement, much like if. The loop executes that statement as long as the expression produces a value that is true when converted to Boolean type.

In this loop, we want to both print the current number and add two to our variable. Whenever we need to execute multiple statements inside a loop, we wrap them in curly braces ({ and }). Braces do for statements what parentheses do for expressions: they group them together, making them count as a single statement. A sequence of statements wrapped in braces is called a block.

Many JavaScript programmers wrap every single loop or if body in braces. They do this both for the sake of consistency and to avoid having to add or remove braces when changing the number of statements in the body later. In this book, I will write most single-statement bodies without braces, since I value brevity. You are free to go with whichever style you prefer.

The variable number demonstrates the way a variable can track the progress of a program. Every time the loop repeats, number is incremented by 2. Then, at the beginning of every repetition, it is compared with the number 12 to decide whether the program has done all the work it intended to do.

Nota: si può scrivere la { su una riga a sé come fanno i C-isti, così:

var number = 0;
while (number <= 12) 
  number = number + 2;

As an example that actually does something useful, we can now write a program that calculates and shows the value of 210 (2 to the 10th power). We use two variables: one to keep track of our result and one to count how often we have multiplied this result by 2. The loop tests whether the second variable has reached 10 yet and then updates both variables (file c2.js). Ovviamente si tratta solo di un esempio, lo stesso risultato si ottiene con Math.pow(2, 10).

// file c2.js (questo è un commento)
var result = 1;
var counter = 0;
while (counter < 10) {
  result = result * 2;
  counter = counter + 1;

The counter could also start at 1 and check for <= 10, but, for reasons that will that will become apparent in Chapter 4, it is a good idea to get used to counting from 0.

The do loop is a control structure similar to the while loop. It differs only on one point: a do loop always executes its body at least once, and it starts testing whether it should stop only after that first execution. To reflect this, the test appears after the body of the loop:

do {
  var yourName = prompt("Who are you?");
} while (!yourName);

This program will force you to enter a name. It will ask again and again until it gets something that is not an empty string. Applying the ! operator will convert a value to Boolean type before negating it, and all strings except “” convert to true. This means the loop continues going round until you provide a name that is not the empty string.

L’esempio può essere eseguito solo nel browser perché c’è la chiamata a prompt; propongo di rifare il precedente usando do al posto di while, file c3.js:

// file c3.js

var result = 1;
var counter = 0;

do {
  result = result * 2;
  counter = counter + 1;
} while (counter < 10)



Posta un commento o usa questo indirizzo per il trackback.



Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:


Stai commentando usando il tuo account Chiudi sessione /  Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione /  Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione /  Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione /  Modifica )


Connessione a %s...

%d blogger hanno fatto clic su Mi Piace per questo: