Lab 11 - JS Arrays, Functions and other Good Stuff!
lab11 folder and open
lab11JS.js it in your code editor.
lab11.html document and be aware of the elements it sets up. You will need
to refer to several of them from the
- Define and call several JS functions
- Practice with Date object
- Start working with JS arrays
- Read from input elements
- Output on the console and write onto the html page itself
Spend a few minutes getting familiar with arrays. Read the w3schools page on arrays.
Exercise 1: Guess what I am thinking!
The user is asked to type, into a text element on the page, one of a pre-decided number of colors. Once they click on a button on the page, the program goes out to produce a random color, among the pre-decided set of colors, and comes back to say if the two colors agree or not.
Define a function, named
guessMyColor(), which will be called from the
onClick event handler
Guess my color! button, when the user clicks on it.
In the body of the function, define a variable to hold an array and populate it
with the colors to be used. For example:
var colors = ["red", "green", "blue", "purple"];
Here is how you can produce a random integer, that you can use as index into the array of colors.
var randomIndex = parseInt(Math.random()*answers.length);
Exercise 2: v2 of Which Day was I born?
In this exercise you will write a new version of this task from your homework #4, that uses arrays. You will get to appreciate how shorter the code can become!
The helper dayNameEnglishAndFrench() function
Define a function named
dayNameEnglishAndFrench() which takes an integer n (from 0 to 6) as input, and returns
a string that contains the name of the corresponding week day in both english and french.
In the body of this function you need to set up two arrays:
- one to contain the names of the days in english, like "Sunday", "Monday", etc, and
- one to contain the names in french, like "Dimanche", Lundi", etc
The main function
Define a function that will be called when the user clicks on the
Tell me button.
In this function, that has been started for you in
lab11JS.js, you will gather the
information from the user, use it to create the right Date object, extract the day the user
was born, and then use the helper function to get the name of the week day. Finally,
present a nice message on the console and the html page itself.