Java Reference
In-Depth Information
}
var lastAdNumber = localStorage.getItem("lastAdNumber");
var nextNumber = getRandomNumber(0, ads.length);
if (lastAdNumber == null) {
lastAdNumber = nextNumber;
} else {
lastAdNumber = parseInt(lastAdNumber, 10);
while (lastAdNumber == nextNumber) {
nextNumber = getRandomNumber(0, ads.length);
}
}
localStorage.setItem("lastAdNumber", nextNumber);
document.write(ads[nextNumber]);
</script>
</body>
</html>
Save this as
ch13 _ question2.html
.
This solution is loosely based on similar questions in previous chapters where you have displayed
random images or messages. In this case you display a different message in the page each time the
user visits it; you'll never see the same message displayed two times in a row in the same browser.
You store the last number of the previously displayed ad in
localStorage
with the
key
lastAdNumber
. So, you retrieve that value and generate the next number with a
getRandomNumber()
helper function (you know this algorithm):
var lastAdNumber = localStorage.getItem("lastAdNumber");
var nextNumber = getRandomNumber(0, ads.length);
If
lastAdNumber
is
null
, you can use the value in
nextNumber
:
if (lastAdNumber == null) {
lastAdNumber = nextNumber;
}
But if
lastAdNumber
is not
null
, you need to generate a random number that is not
lastAdNumber
.
So first, you convert
lastAdNumber
to a number with the
parseInt()
function:
else {
lastAdNumber = parseInt(lastAdNumber, 10);
while (lastAdNumber == nextNumber) {
nextNumber = getRandomNumber(0, ads.length);
}
}
Then you use a
while
loop to generate a unique random number. The loop iterates if
lastAdNumber
is
equal to
nextNumber
, and it continues to do so until the next number is different than
lastAdNumber
.
Once you have a unique next number, you store it in
localStorage
and display the ad in the page: