Using Indexed Arrays
You can practice working with arrays interactively using the web browser Console window.
Lesson Setup Instructions
This lesson's activities uses the console interactive mode.
Steps:
-
Open in the web browser the console.html file found in the completed folder.
Alternatively any open web page can be used.
-
Open the Console window in the web developer tools.
For details see the Using Web Browser Developer Tools to Learn lesson in the Getting Started section for interactively accessing the Chrome Console window.
1. Lab: The Confucius Says array.
-
In the Console window enter the following …
var quotes = []
quotes
quotes.length
quotes.push("Be not ashamed of mistakes and thus make them crimes.")
quotes
quotes.length
-
In the Console window enter the following …
quotes.push("Before you embark on a journey of revenge, dig two graves."); quotes.push("Everything has its beauty but not everyone sees it."); quotes.push("Forget injuries, never forget kindnesses."); quotes.push("He who will not economize will have to agonize."); quotes.push("I hear and I forget. I see and I remember. I do and I understand"); quotes.push("Ignorance is the night of the mind, but a night without moon and star."); quotes.push("It does not matter how slowly you go so long as you do not stop."); quotes.push("Our greatest glory is not in never falling, but in getting up every time we do."); quotes.push("Learning without thought is labor lost; thought without learning is perilous."); quotes.push("Real knowledge is to know the extent of one's ignorance."); quotes.push("Choose a job you love and you will never have to work a day in your life.");
-
Expand the array output line.
-
In the Console window enter the following …
quotes.length
quotes[0]
quotes[4]
quotes[12]
-
In the Console window enter the following …
var randomQuoteIndex = Math.floor(Math.random() * quotes.length + 1)
randomQuoteIndex
quotes[randomQuoteIndex - 1]
randomQuoteIndex = Math.floor(Math.random() * quotes.length + 1)
randomQuoteIndex
Your
randomQuoteIndex
values may be different.
2. Lab: The Scores array.
-
In the Console window enter the following …
var score1 = Math.floor(Math.random() * 100 + 1)
score1
var score2 = 55
score2
var scores = [score1, score2, 75]
scores
-
In the Console window enter the following …
scores.push(Math.floor(Math.random() * 100 + 1)); scores.push(Math.floor(Math.random() * 100 + 1)); scores.push(Math.floor(Math.random() * 100 + 1)); scores.push(Math.floor(Math.random() * 100 + 1)); scores.push(Math.floor(Math.random() * 100 + 1)); scores.push(Math.floor(Math.random() * 100 + 1)); scores.push(99);
-
In the Console window enter the following …
scores[2]
scores[2] = 25
scores[2]
scores[scores.length - 1]
scores[scores.length - 1] = (score1 + score2) / 2
scores[scores.length - 1]
scores
-
In the Console window enter the following …
var currentIndex = 0;
scores[currentIndex];
scores[currentIndex + 2];
scores[currentIndex + 12];