28
CS1046 – Lab 3 Timing: This lab should take you 90 to 120 minutes. Ex. 1: 20, Ex. 2: 30, Ex. 3: 20, Ex. 4: 15 = (85 mins) Objectives: By the end of this lab you should be able to: Define the terms: script and program Identify an object and its properties, methods and events Identify the document object and at least one of its properties, one of its events and one of its methods Create and link an external script file with the extension .js and attach it to an HTML webpage Identify and write a JavaScript statement Identify, explain the purpose of, and write a JavaScript comment Explain the purpose of a variable Declare a variable Assign a value to (store something in) a variable Distinguish between the three data type of a variable Properly use single and double quotes when working with String variables Display the value of a variable on a webpage Follow the six rules for naming a variable Identify an array and identify the situations in which you would use an array Create and fill an array with values Retrieve a value(s) from an array Write a valid expression involving variables and arithmetic and concatenation operators Exercise 1 – Incorporating JavaScript code into your HTML webpage and using the document object 1. When we write JavaScript we are writing a script or a program. Both of these terms really just mean: a series of instructions. Thus, your favourite recipe for apple pie could also be considered a 1

lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

  • Upload
    lamcong

  • View
    217

  • Download
    0

Embed Size (px)

Citation preview

Page 1: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

CS1046 – Lab 3Timing: This lab should take you 90 to 120 minutes. Ex. 1: 20, Ex. 2: 30, Ex. 3: 20, Ex. 4: 15 = (85 mins)

Objectives:

By the end of this lab you should be able to:

Define the terms: script and program Identify an object and its properties, methods and events Identify the document object and at least one of its properties, one of its events and one of its

methods Create and link an external script file with the extension .js and attach it to an HTML webpage Identify and write a JavaScript statement Identify, explain the purpose of, and write a JavaScript comment Explain the purpose of a variable Declare a variable Assign a value to (store something in) a variable Distinguish between the three data type of a variable Properly use single and double quotes when working with String variables Display the value of a variable on a webpage Follow the six rules for naming a variable Identify an array and identify the situations in which you would use an array Create and fill an array with values Retrieve a value(s) from an array Write a valid expression involving variables and arithmetic and concatenation operators

Exercise 1 – Incorporating JavaScript code into your HTML webpage and using the document object

1. When we write JavaScript we are writing a script or a program. Both of these terms really just mean: a series of instructions. Thus, your favourite recipe for apple pie could also be considered a script or a program (except it uses a human to execute it rather than a computer). The manual for installing your dishwasher is also an example of a program/script. One of the only real requirement when writing a script is that the instructions are clear and comply to some syntax rules (for example, when writing a recipe, you follow the rule to use either all metric measurements or all imperial measurements, to mix them would be confusing). Also, the script should achieve a clear goal, for example, a recipe for apple pie should actually produce an apple pie at the end of the instructions, not chicken noodle soup. A script that creates an online calculator in a webpage should produce the correct answers when someone presses the necessary buttons on your webpage.

1

Page 2: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

2. To create a script we need to gather together the necessary parts. Two key parts we will need are objects and variables:

a. An object is a thing, such as a button or a text box on a webpage. It could also be an element (remember elements are the opening and closing HTML tags and the stuff in between them). An analogy from our Apple Pie recipe example would be the pastry. The pastry would be an object.

b. A variable stores or holds data (it is kind of like a bucket). A variable can point to an object or to a simpler thing that holds a value (either a numeric value or a text value), such as the width of a webpage button, the URL for the webpage. In our Apple Pie recipe example, the amount of water or flour used to make the pastry might be held in variables such as amtOfFlour, amtOfWater.

Now let us take a closer look at Objects. 3. Objects

a. An instance of an object is ONE actual object. For example, one actual button on a webpage would be an instance of the button object. Another example would be student objects. An instance of a student object would be the actual student named “John Smith”.

b. Each instance of object can have its own:i. Properties – a characteristic of the object For example, some properties of a

button are: backgroundColour, caption and name.ii. Methods – the things that people need to do with the object. Often methods

can get values of the object’s properties OR set the values of object’s properties. For example, you might want to make change the colour of the button to pink, so you use a method called setBackgroundColor(“pink”).

iii. Events – the way people interact with the object For example, the onclick event fires (activates) when a person (user) clicks on the button.

c. One of the most important objects in JavaScript is the document object. It lets you access and change the content on a webpage

i. Some of the document’s properties are the title, the URL and the date last modified (lastModified)

ii. Some of the document’s methods are write() which adds new content to the webpage and getElementById() which accesses an HTML element by the id you give it.

iii. Some of the document’s events are load which activates/fires when the user first loads your page into his/her browser or keypress which activates/fires if the user presses a key on the keyboard.

d. Now let’s write some JavaScript to make the document object do something.4. Using the Chrome browser, go to this webpage:

http://www.csd.uwo.ca/~lreid/cs1046/labs/lab3/lab3ex1a.htmlRight click and view the source for this page.

5. Create a new folder called lab3.Open Notepad and then save the file (in the lab3 folder) as yourwesternuseridlab3ex1a.html (eg.

2

Page 3: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

jsmith2lab3ex1a.html). It is important to save the file as an .html and not .txt file. Consult Lab 1 Exercise 5 if you experience difficulty.

6. Using the Chrome browser, go to this webpage: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab3/lab3ex1.css and copy the code into your lab3 folder, using Notepad to create a new file, paste the css code in and give this new file the name: lab3ex1.css (It is important to use this name, because we have already linked this css file to the HTML file)

7. Using Notepad, open the HTML file you just created. We are going to add our first JavaScript code to this page. Move to just after the </h2> HTML tag but before the </body> tag in your lab3ex1a.html file and add the following:<script src="writingtopage.js"></script>This line instructs the system to insert the JavaScript code found in the writingtopage.js file into our HTML webpage.

8. Try opening your lab3ex1a.html in Chrome, notice how nothing has changed. This is because you have not created the JavaScript file yet. Now open Notepad and create a new file and save it in your lab3 directory as writingtopage.js

9. Add the following line to writingtopage.js:document.write('Good Afternoon YourName');Change YourName to your actual name. Make sure you spell everything correctly, remember to include the single quotes and brackets around Good Afternoon YourName and remember to end the line with the semicolon, it is important!

10. Now try refreshing your lab3ex1a.html file. Every time you write some code, you should verify that it works. Even the best programmers in the world need to check to see if their code executed properly. By refreshing your webpage, you are executing/running the code to see if it works. You should now see the greeting (Good Afternoon YourName) in the correct spot. This is because we told the document object that we wanted to write to it, immediately after we displayed the <h2> heading. The line: document.write('Good Afternoon YourName'); is called a statement in programming. A statement is a single instruction. In JavaScript, the semicolon indicates the end of a statement. Do not forget to use the semicolon. It is also good practice to always put each statement on its own line. Do not write a program like you would with a paragraph, all running together, instead put each statement on a single line.

3

Page 4: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

11. Let’s add another statement to our .js file. Right after the document.write('Good Afternoon YourName'); statement add the statement: document.write('<h1>Would you like some cupcakes?</h1>'); So your .js file should look like this:

Save your .js file and refresh your HTML page to observe the change. Notice that your page knows to process the <h1> tag properly (i.e., it treats it as markup and, as a result, it is not displayed).

12. One thing all good programmers do is comment their code. Commenting is adding explanations that do not get executed (i.e., the browser does not really care if you add them) but comments will help other programmers understand your code better. Comments also help you remember why you did what you did and help other programmers understand your code. Let’s add some comments. If the comments you feel you should add will span more than 1 line (multiline comments), put a /* to start them and a */ to indicate the end of them. Go into your .js file and add the comment below to the top of the file (before your 2 statements) and then save your file:/* This is the first JavaScript code that I have written Written by: Your NameWritten on: The date*/

13. For comments that will only be one line, you can use two slashes // Add the following comment to the very end of you .js file and save the .js file//The end of my first program

14. Your .js file should now look like this:

4

Page 5: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

15. Refresh/reload your HTML page; you should notice that nothing changed. Remember comments are not executed, they are just like post-it notes to yourself that serve as a reminder (similar to when you put notes in the margins of a textbook).

16. If you want to read a really great short little explanation of objects, check out this article http://html.net/tutorials/javascript/lesson9.php

Congratulations, you now can:

a. Add the external <script> tag to an HTML file in order to include JavaScript statements in your webpage.

b. Use an object, the document object, in a webpage.c. Execute one of the document object methods, the write() method.d. Identify a JavaScript statement.e. Identify two different types of JavaScript comments.f. Verify to make sure your code executed properly.

5

Page 6: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

Exercise 2 – Declaring variables, assigning values to variables and working with numeric variables

A variable is a container for data. For example, if you wanted to create an online calculator program and the user wanted to see the result of 456 X 34, you would need one variable to hold the value 456, another variable to hold the value 34 and a third variable to hold the resulting answer. If you remember algebra, you already have a vague idea of what a variable is. One noticeable difference is that programmers try to pick more descriptive names than your math teacher would have picked (likely your math teacher picked names like: x, y and z).

1. Before you can use a variable, you need to create space for that variable. This is done by declaring the variable, for example: var quantity;The statement above is a variable declaration (we are creating space in memory for a variable called quantity):

Things to note about the above declaration:a. var is a keyword it is a special word that the JavaScript interpreter (tool that checks

your code before displaying it in a browser) uses to say “I am going to create memory space for a new variable” . This is the only thing you can do with the word var. You cannot use any keywords as variable names, this will confuse the interpreter. Thus you can NOT do this: var var;

b. quantity is the name of the variable. There are rules and suggestions for variable names in JavaScript:

It cannot be a keyword (like var) It must start with a letter, or a dollar sign ($), or an underscore It cannot start with a number It can contain numbers, letters, dollar signs or underscores but no other

characters (e.g. my.home.town would be an invalid variable name, while my_Home_Town1 would be valid name )

It is case sensitive, so quantity and Quantity are two DIFFERENT variables It should be a descriptive name, so rather than this:

var w; a more appropriate name might be:var width;

If your variable is made up of more than one word, use a capital letter for the first letter of every word after the first word, for example, rather than this:var firstname;do this instead:var firstName;

c. The declaration must end with a semi colon;

6

Page 7: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

2. Open the file: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab3/lab3ex2a.html and save the source (the HTML tags) to your lab3 folder, in a newly created file called lab3ex2a.html. View it in the browser. Notice how this page should calculate the total price of cupcakes based on the number the user puts in the text box.

3. In the HTML source, right after the line that creates the button <button>… </button> add the following line:<script src="calculating.js"></script> This line of code instructors the interpreted to include the file calculating.js in our HTML file.

4. In Notepad open a new file and save it in your lab3 folder as calculating.js5. Now we are going to declare the variables we will need to do the calculation. We will make one

variable to hold the number of cupcakes, another variable will hold the cost per cupcake and the third variable will hold the resulting calculation. So in the file: calculating.js add the following to declare these 3 variables:var costPerCupcake;var amountOfCupcakes;var totalCost;Take note of the fact that we used descriptive names for the variables and followed the rules for naming them.

6. Save both files (i.e., lab3ex2a.html and calculating.js file) and then reload lab3ex2a.html in the browser. Notice that nothing has changed. This is because we have only declared the variables but not used them yet.

7. Next, we will add some code to do our calculation; first, we will enter the cost per cupcake as 3 dollars. You ALWAYS put the variable on the left side and the value you want to store into it on the right side. So add the following line after the declaration lines:costPerCupcake = 3;

8. Then add the code below to get the number of cupcakes from the text box on our webpage:amountOfCupcakes = document.getElementById("amtToGet ").value;NOTE: for the above line of code, we use the id for the textbox to access it as an object and then use the value property (.value) to retrieve the number the user entered in the box.

7

Page 8: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

9. Then to calculate the total cost for the cupcakes, add this line:totalCost = amountOfCupcakes * costPerCupcake;NOTE: in the line above the multiplication operator (*) is used but there are other arithmetic operators that exist. Assume we have three simple variables x, y and z, here is a table to help you understand the common arithmetic operators:var x;var y;var z;x = 10; //so the variable x hold the value 10 nowy = 2; //and the variable y holds the value 2 now

If, right after the above 5 statements, we did this JavaScript statement(s):

THEN the value in z would be:

Operation Notes

z=x+y; 12 Additionz=x/y; 5 Divisionz=x*y; 20 Multiplicationz=x-y; 8 Subtractionz=x%3; 1 Modulus (Divides and

returns the remainder)x++; Increment by 1 x will have 11 in

it after statement is executed.

x--; Decrement by 1 x will have 9 in it it after statement is executed.

x=x+y;z=x+y;

14 Demonstrating that variables can be overwritten x takes on the value 12 in first statement and thus z = x (now 12) + y (still 2), so z is now 14

10. Finally we need to display the answer to the user, To display the output, add the following statement:document.write(totalCost);

11. Now save your calculating.js file and reload your HTML webpage in your browser.

8

Page 9: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

12. Make sure your code displayed the correct total of 3. NOTE: initially, the textbox has 1 in it (the default value), so the total cost displayed will be 1 * 3 3, we still have some work to do before we can change the number of cupcakes in the textbox and have it calculate that cost). If it did not work, it could be a very small error; for example, when I first created this lab, I incorrectly typed: getElementByID rather than getElementById and my code wouldn’t work and it took me a while to figure it out. I have indicated in red what I did wrong getElementByID vs getElementById. Your code should look like this:

var costPerCupcake;var amountOfCupcakes;var totalCost;costPerCupcake=3;amountOfCupcakes =document.getElementById("amtToGet").value;totalCost = amountOfCupcakes * costPerCupcake;document.write(totalCost);

13. Change getElementById to getElementByID then save and reload your html page again and notice that the page does not work anymore.

14. You can use Google Chrome to find out why your page is not working. To do this, right click on the webpage and select Inspect Elements (or it might just be called Inspect). Next click on the Sources tab and click on the calculating.js file and then you should be able to see which line is causing the problem. The diagram below shows what it would look like. The area highlighted in yellow emphasizes the problem:

15. Click on the X to get rid of the inspection window and change the code back so that it works (i.e., change getElementByID to getElementById and resave the file and reload the page)

9

Page 10: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

16. Now right under the line document.write(totalCost) add the line:document.write("totalCost");so your code should look like this now:

var costPerCupcake;var amountOfCupcakes;var totalCost;costPerCupcake=3;amountOfCupcakes =document.getElementById("amtToGet").value;totalCost = amountOfCupcakes * costPerCupcake;document.write(totalCost);document.write("totalCost");

17. Reload your webpage in the browser and watch what happens. Notice that if you put quotes around text (even if it is a variable name) it displays the text exactly, not the value inside the variable. So if you want to display a variable, do NOT put quotes around it. If you want to display text, do put quotes around it.

18. Now let us make the output a bit nicer, update your JavaScript file so it looks like this:

var costPerCupcake;var amountOfCupcakes;var totalCost;costPerCupcake=3;amountOfCupcakes =document.getElementById("amtToGet").value;totalCost = amountOfCupcakes * costPerCupcake;document.write("<p><h1>Total Cost: ");document.write(totalCost);document.write(" dollars </h1></p>");

19. Reload the HTML and observe the difference.20. Figure out how to modify your program (change something in the .js file) so that cupcakes are

now 4.50 per cupcake. 21. We still have one BIG problem. Right now, no matter what value the user puts in our textbox,

our script always only calculates for the initial value of 1 cupcake. Try putting 3 in the textbox and press the button. Notice that it still just displays the cost for the default value of 1 cupcake. To fix this issue we need to change the tag for the button, so that when the button is clicked it does “something”. We will give the name of the “something” that it does: calcCost. In your HTML file, change the Calculate Cost button tag so that it now looks like this (new part is indicated in red):<button onclick="calcCost()">Calculate Cost</button>Remember JavaScript syntax must be precise, so make sure you type the line exactly as it appears above.

10

Page 11: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

22. Try reloading your HTML page, notice that it still does not work. This is because we instructed the system to do calcCost when the user clicks on the button. calcCost is called a function (a function is just a little task) BUT we have not yet declared/indicated what the function called calcCost should do. We will do that in four steps:

a. Create the header for the function b. Use the opening curly brace to show where the group of statements beginc. Put the body of the function next (the series of instructions for the task, you have

already written them!)d. Use the closing curly brace to show where the group of statements ends

23. The steps are shown below. Update your calculating.js file so that it looks like this (the new parts are indicated in red):

24.

Now try reloading it in the browser and make sure your program correctly calculates the cost based on the number of cupcakes (it might open a new page for this info, we will look at how to fix this type of problem later on).

CONGRATULATIONS! You have written your first truly functional piece

of JavaScript code, you are now a programmer! In order to be a GOOD programmer, you should add some comments and properly indent your code. This will not change how your program functions, but it will make the program a lot easier to understand. Think of it as a dirty refrigerator. Cleaning it up does not change the way the fridge works, but it makes it much easier to use ! We always indent the code a few spaces between the opening function functionName() { and the closing } as it makes our code easier to read.

11

function calcCost() {var costPerCupcake;var amountOfCupcakes;var totalCost;costPerCupcake=4.5;amountOfCupcakes =document.getElementById("amtToGet").value;totalCost = amountOfCupcakes * costPerCupcake;document.write("<p><h1>Total Cost: ");document.write(totalCost);document.write(" dollars </h1></p>");}

Page 12: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

25. Comment and indent and put white space (blank lines to make it more readable) into your code so that it looks like this:

12

function calcCost() {

//This function will calculate the cost of cupcakes based on what the number the user//enters in the text box

//Variable Declaration var costPerCupcake; var amountOfCupcakes; var totalCost;

//do calculations costPerCupcake=4.5; amountOfCupcakes =document.getElementById("amtToGet").value; totalCost = amountOfCupcakes * costPerCupcake;

//display answers document.write("<p><h1>Total Cost: "); document.write(totalCost); document.write(" dollars </h1></p>");} //end of function

Page 13: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

Congratulations, you now can:

Declare a variable Assign a numeric value to a variable Assign a mathematical expression to a variable using arithmetic operators Output the value in a variable Identify when the document.write will display the contents (value) of the variable and

when it will display text. Use the Inspect Element feature in Google Chrome to find which line of your JavaScript

code is causing an error. Add comments/white space/indentation to your code

13

Page 14: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

Exercise 3 – Working with String Variables

In the previous example, we were working with numeric variables (i.e., variables that hold numbers). We can also use variables to hold textual data. These types of variables are called string variables. We will add string variables to improve our cupcake webpage.

1. Download the following 2 files and save them in your lab3 folder: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab3/lab3ex3a.html http://www.csd.uwo.ca/~lreid/cs1046/labs/lab3/calculatingtwo.js

2. Open the HTML file in the browser to make sure it works and then in order to edit the files, open them both in Notepad.

3. In calculatingtwo.js, make a variable to hold the type of currency. Add the following line to declare a string variable right underneath the other declarations:var currencyType;

4. Replace the line that says document.write (“ dollars </h1></p>”); with these three lines:currencyType="Euros";document.write(currencyType);document.write("</h1></p> ");

5. Notice that you must always put quotes around your strings when putting them in a variable. Reload your webpage and make sure it says Euros now instead of dollars.

6. Figure out how to modify your variable so that the currency is now YenThere is just one string operator, the + symbol. This symbol is called the concatenation symbol and it joins strings together. For example, if you had:var firstName;var lastName;var wholeName;firstName="Homer";lastName = "Simpson";wholeName=firstName+lastName; //Line AThen the variable wholeName would contain the string: "HomerSimpson". This might not be exactly what you want; you probably would want a space between Homer and Simpson. There are a few ways you could do that. We could change the last line above to this:wholeName= firstName + " " + lastName;or we could create another variable and do the following:var space= " ";wholeName=firstName+space+lastName;

14

Page 15: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

7. NOTE: there are some tricks to watch out for with strings and the concatenation operation (+), look at the following variables. Here is code with different scenarios of what can happen using the + operator:var w;var x;var y;var z;w=7;x=9;y="7";z= "9"var result;result = w+x; //result would the number 16result = y+z; //result would have the string "79"result = w+y; //result would have the string "77" because if one of the variables on either side of the + is a string, then the answer is a stringresult=w*x; //result would have the number 63;result=y*z; //ERROR (you cannot multiply strings)

8. NOTE: there are also some tricks to watch out for with quotes, for example:var firstName;var lastName;firstName= "Maggie"; //double quotes are fine as long as you use at both ends of stringlastName='Simpson'; // single quotes are fine as long as you use at both ends of stringfirstName="Maggie'; //ERROR, can’t mix up the set of quotes, just use one or the otherfirstName= "Maggie's Book”; //This is okay, this is how you put an apostrophe (single quote) in a string, need to use double quotes on the outsidefirstName= '"To be or not to be" by William Shakespeare '; // this is okay, this is how you put double quotes in a string, need to use single quotes on the outside

9. Go back to your calculatingtwo.js file, and just below the comment //display answers put the tags into a string variable called myOpenTags and myCloseTags as follows:var myOpenTags;var myCloseTags;myOpenTags="<p><h1>";myCloseTags="</h1></p>";

10. Create a string variable (give it a reasonable name) and store the phrase Total Cost: into it.11. Replace the document.write() lines so that they ONLY use variables and so that the output looks

correct (e.g. you have 3 Yen, NOT 3Yen)12. Make one more variable called myProgram and put the value "YourName's first program! " into

it. Make sure the apostrophe is displayed. Use the document.write command to have this statement appear after the total cost of the cupcakes.

13. Reload your program into your browser to make sure it works.

15

Page 16: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

In addition to numeric and string variables, JavaScript also allows the creation of Boolean variables. Unlike a string variable or a numeric variable that can contain one of an almost infinite number of values, a Boolean variable can only be one of two values: true or false. This variable type will be discussed in detail in a future lab.

Congratulations, you now can:

Assign a string value to a variable Concatenate strings Put an apostrophe inside a string Put double quotes inside a string Output a string

16

Page 17: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

Exercise 4 – Creating arrays, assigning arrays, accessing arrays

1. An array is a special type of variable that can hold more than one value. Arrays can be used in situations where a programmer needs to store related (similar) items collectively. For instance if you wanted to keep track of grocery items, rather than having the code shown below in box A, you could replace it with the code shown in box B.

Think of an array as a list of values. Arrays are one of the most useful data structures that computer scientists have. Let’s make a list of cupcake flavours. Open the webpage you were just working on or use this one: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab3/lab3ex4a.html and copy it to your lab3 folder and open the file in Notepad. Right after the line where you create a button in the HTML file but above the <script> tag, add the following code to create a dropdown list of cupcake flavours:

<h1>Our Flavours</h1><select id="cupcakeTypes"> <option value="rasp">Raspberry</option> <option value="blue">Blueberry</option> <option value="choco">Chocolate</option></select>

2. Now save your file, open it in the browser and make sure the dropdown box worked.3. Copy the file http://www.csd.uwo.ca/~lreid/cs1046/labs/lab3/calculatingthree.js to your lab3

folder and open it in Notepad. 4. In your HTML file, change the <script> tag so that it points to calculatingthree.js5. Edit the calculatingthree.js file and in it declare an array to hold the cupcake types by adding the

following line just below your other 3 declarations:var cupcakeTypes=[];

6. Then immediately after the declaration you just made, add the following line to fill the array with cupcake flavours:cupcakeTypes=['Red Raspberry','Berry Berry Blueberry','Cherry Chocolate'];

17

CODE A

var item1;var item2;var item3;var item4:var item5;item1=’eggs’;item2=’cheese’;item3=’milk’;item4=’bread’;item5=’cookies’;

CODE B

var items:items =[‘eggs’,’cheese’,’milk’,’bread’,’cookies’];

Page 18: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

7. Reload your HTML file and make sure your button still works but notice that nothing else has changed. This is because all we have done is put the values in the array, we have not used them yet. Now that our array is holding our values, we will at some point want to access these values. For now, because we do not have enough tools to do much with our array, all we are going to do is display each array value. To access an individual value in an array, you have to use an index. The index is a value that tells us which item to access. The index is always an integer value and always surrounded by square brackets. Computer Scientists like to start counting at 0, so cupcakeTypes[0] would be the very first value (in our case: Red Raspberry).

8. Add the following 2 lines to calculatingthree.js near the end of the code, just before the } ://display types of cupcakes

document.write( cupcakeTypes[0] );9. Save your calculatingthree.js file, reload your HTML file again and click on the button and make

sure the first type of cupcake appears. 10. Now add 2 more lines to the calculatingthree.js file that will make the other 2 types of cupcakes

show up on the screen. Remember that the index value starts at 0, so if you want to see the third type of cupcake, the index will NOT be 3. Figure out what value it should be.

11. Save your calculatingthree.js file and reload your HTML file and click on the button to make sure the three types of cupcakes appear on the screen. In a few weeks you will learn how to access each item in an array quickly, so that you could display 1000s of cupcake types by only writing 3 lines of code!

12. You can also assign just one item in an array individually. We will now add one more cupcake type, a fourth type (so index would be [3]), in your calculatingthree.js file. You will assign this value near where you are displaying the values, rather than in the line where you put all the values in initially. Add the following line right after the location where you just displayed the third cupcake:cupcakeTypes[3]="Your Western User Id’s Tootie Fruity";

13. Add a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor.

14. Add a line that will change (overwrite the old value with this new value) the value in the second item of the array to be "Butter Pecan"

15. Now add the line:document.write(cupcakeTypes.length);

16. Save your .js file and reload your .html file and notice that the .length property of an array will tell you how many items are in an array. This number should be five.

17. Add a comment to the top of the calculatingthree.js file that has Code written by your name (userid) at the top, for example://Code written by: Homer Simpson (hsimpo44)

18. Now just for a bit more practice, declare a string variable called allTheTypes near the top of the file with all the other declarations. Then move down to just after where you put a value in the fifth element in the array (the one at [4]) and write the code that will concatenate the 5 cupcake types from the array together and store them all together in that single string variable with <br> codes between them. Thus, the line should START with this:

18

Page 19: lreid/cs1046/labs/lab3/lab3.docx  · Web viewAdd a line to create a fifth cupcake type in the array and give it the value of your favourite cupcake flavor. Add a line that will change

allTheTypes=cupcakeTypes[0] + "<br>" + ….. ; //you figure out what to put for the ….

19. Then add the statement:document.write(allTheTypes);This statement should display something similar to the following on the page:

Congratulations, you now can:

Declare a variable that will hold an array Fill the values of the array in a single line Fill the value of one item of the array Access a specified item first item in the array using the correct index value Use the length property to get the number of values in an array Change the value of an array item

HAND THIS WORK INTO OWL IN ORDER TO GET YOUR LAB MARK.

1. Go into owl and for Lab 3, submit your last file, the one called lab3ex4a.html AND submit the file calculatingthree.js so that we can check that your code is working properly.

19