# 9 Review Questions | # 9 Assignment |
Up to now, we have worked with variables that contain strings, integers, decimal values, and even variables that represent objects such as windows. But one big limitation is that they all can contain only one item at a time. If we say var x = 5; then later say var x = 6; the 5 is gone. Some tasks are done more easily if we can store an entire list of data in an array, and even going beyone that, we could store data in rows and columns just like in a spreadsheet, or a database. Using an array as either a list or a table, we have the ability to reference all the data in the array by the same name. And our ability to perform looping, gives us the power to handle large amounts of related data, which is what computer do best!
For example, suppose your teacher has 32 students who all took the Lesson 8 review questions, and reported their scores. If we store all these scores in a list, or array named 'quiz8Scores', then we could use a loop that repeats 32 times to let the teacher input the 32 scores, then go back through and display all 32 scores, or do another loop to add up all 32 scores and divide the total by 32 to find the class average. We could search the list to reward all students who got either 9 or 10 for their score, and we could even move the scores around to put them in order. So you see, lots of things are simple if you know how to use arrays, so lets take a look at how its done!
An array in JavaScript is actually an object, and we use the 'new' keyword to create an array object. For example:
quiz8Scores = new Array(32);
Here is a breakdown of what is going on here.
Some things that will seem a little ditzy if you are already used to programming in another language - wierd JavaScript to know and love:
If you assign a value to an array element that has not yet been created, JavaScript will create that element for you and let you assign it a value. Don't even think about doing that in Java or in C++.
Arrays in JavaScript can hold data of different types. This could be hazardous to your programming health, so I probably shouldn't even tell you this. Trust me that other programming languages are not this loose on the types of data in an array. For example, if one student did not take the quiz, then we could enter 'absent' instead of a number score. That can cause some programming complexity when we go back in the find the average, so use that bit of info with caution.
First let's look at how to store info in this array. Since we know the number of students, we can use a for loop to prompt for all 32 of the scores. This might get tedious for the person who has to type in all those numbers, but the code is pretty simple. We will use i as our loop control variable, and also use i as our index to tell the computer which element to store the number in each time.
function fillArray() { // create a new Array object and get data from user quiz8Scores= new Array(32); // creates space in memory and gives it a name for ( var i = 0; i < 32; i++ ) { // for loop to ask for each score quiz8Scores[i] = prompt("Enter score for student " + i, ""); } // end function |
This could also be done with a different type of looping such as do...while... depending on how you plan to use the array. Often, programmers will set aside more elements than they really need, just because they don't want to run out of room.
Printing out the list of scores can also be done using a loop. We just change the prompt() method to something like document.writeln() and go through the loop the same way.
for ( var i = 0; i < 32; i++ ) { // for loop to display each score document.writeln(quiz8Scores[i]); |
The important things to remember are:
Another example is a deck of cards. Lets think of a deck of cards as being a list of the cards in a deck, going from card[0] to card[51]. Since the cards in the suit hearts are just the same as the cards in spades, diamonds, and clubs, we can use a set of loops to fill cards 0-12 with hearts ace through king, then another loop to fill cards 13 to 25 with diamonds ace through king, and so on. The demo program will:
Click here to open the Card Game Window
Here is the code for the first function that creates an array of cards and fills the empty array with some data that looks like a deck of cards, at least to us humans.
<script language="JavaScript"> function makeDeck() { // create and fill the deck var viewCardsWindow = window.open("", "", "HEIGHT=600,WIDTH=200 scrollbars=yes"); for ( var i = 0; i < 13; i++){// make 13 hearts switch (i) { case 0: deck[i] = "Ace of Hearts"; break; case 10: deck[i] = "Jack of Hearts"; break; case 11: deck[i] = "Queen of Hearts"; break; case 12: deck[i] = "King of Hearts"; break; default: deck[i] = (i + 1) + " of Hearts"; break; } // end switch } // end for loop for Hearts //JavaScript will convert the number i to a string to do the concatenation //I handle setting the value of the cards with the % operator - the remainder of div by 13 for ( var i = 13; i < 26; i++){ deck[i] = (i%13 + 1) + " of Diamonds"; // make 13 diamonds switch (i%13) { case 0: deck[i] = "Ace of Diamonds"; break; case 10: deck[i] = "Jack of Diamonds"; break; case 11: deck[i] = "Queen of Diamonds"; break; case 12: deck[i] = "King of Diamonds"; } // end switch } //end for loop for Diamonds // All the other suits are done just like the Diamonds so I omitted the view of that code |
We also need to see how to decide if we have drawn a winning card or not. The face cards all contain strings with no numerical digits, so the first thing I did hter is use the parseInt() function to attempt to convert the card to a digit. parstInt() will try, and as long as there are digits it will convert to integer. But when the very first character is a letter, or something besides a digit, it gives up and returns a cute value called "NaN" meaning Not a Number. Then a function called isNan() is called to see if the value returned was NaN. If so then we have a face card, since all the others would return a number. Here is the code to draw a card and check for a winner.
function drawCard(form) { |
Computers can be useful in doing searches. If data is stored in an array it can be quite easy to do a search. The simplest kind of searching is just to start with the first item in an array, which is array[0], and compare it to the target (the target is the item you are looking for). If they match, you are done. If not, move on to the next item and continue comparing until you get to the end of the array. If you get to the end, and no match, then the item is not there. This is called a sequential search, since it just goes in order.
Code this by setting up a for-loop starting at position 0 going to the end. Add an 'if' statement using == to see if the array item is equal to the target. If so, you can use the break; statement to stop the computer from continuing to search.
Sorting items in an array is one of those things that is best done by a computer. When you think about arrays, they can be very large collections of data, and usually it is in the same array because it is logically in the same category. Things like people's names, the names of all the CD's in your collection, the birthday's of all your friends, and lists of number. Usually we want to see such data, especially if there is LOTS of it, in order.
There are many methods to use in a computer program to get the data in order, or sorted, and the bubble sort, while rather slow, is an easy one to learn and understand. One good feature of the bubble sort is that it can detect when the array is already in order and exit early, saving time. Here is basically how it works:
This is what the code looks like for an array of 10 items, but just change the size and it will work for any size array you have.
function sortDemo(){ var list = new Array(10); // create an array called list of 10 items // fill the array with some random numbers from 1 to 100 var sortWindow= window.open("", "", "HEIGHT = 500, WIDTH=400 "); for (var i = 0; i < 10; i++) list[i] = Math.floor(Math.random() * 100) +1;// formula for integers from 1 to 100 // now display the list in a window, RANDOM order sortWindow.document.write("Array in Original Order <br>"); for (var i = 0; i < 10; i++) sortWindow.document.write(list[i]+"<br>"); // now use two for-loops to do a bubble sort var temp; // temp storage space used for swapping var end = 10 - 1; // Yes, Virginia, that means 9 var swapsMade = "yes"; while (swapsMade =="yes") { // repeat this loop as long as items are out of order swapsMade = "no"; // maybe the work is not all done for(var i = 0; i < end; i++) { // note this loop stop one shy of the end of the list if (list[i] > list[i+1]){ // compares two adjacent items - swap if out of order // three steps needed to swap temp=list[i]; list[i]=list[i+1]; list[i+1]=temp; // swap done swapsMade = "yes"; // still more work to do } // end of if block } // end for loop for sorting end -=1; //shorten the list by 1 each time through } // end of while loop, no use continuing if no items out of order // now show list again - in order this time sortWindow.document.write(" <br> Same Array in Sorted Order" + "<br>"); for (var i = 0; i < 10; i++) sortWindow.document.write(list[i]+"<br>"); // Whew - done } // end function sortDemo |
Click here to run a demonstration