Utilizzo del loop con il for. Questo codice in particolare può essere utile per leggere i tweets.
var tweetString = "";
var tweets = ["Hi everyone!", "I love cornflakes!", "Night night :)", "Sweet dreams!"];
for (var i = 0; i < tweets.length; i++) {
tweetString = tweetString + "<p>" + tweets[i] + "</p>";
}
document.getElementById("tweetDiv").innerHTML = tweetString;
Qui invece si usa il while per giocare col computer e vedere in quante volte indovina il numero inserito.
<p>How many fingers are you holding up?</p>
<p>
<select id="myNumber">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<button id="guess">Guess!</button>
</p>
<script type="text/javascript">
document.getElementById("guess").onclick = function() {
var myNumber = document.getElementById("myNumber").value;
var gotIt = false;
var numberOfGuesses = 1;
while (gotIt == false) {
var guess = Math.random();
guess = guess * 6;
guess = Math.floor(guess);
if (guess == myNumber) {
gotIt = true;
alert ("Got it! It was a " + guess + ". It took me " + numberOfGuesses + " guesses.");
} else {
numberOfGuesses++;
}
}
}