Sunteți pe pagina 1din 12

Questions for JavaScript Lesson 1

1. Which of the following is/are legal variable names?


a) this is a legal name b) is_this_legal? c) temp164
d) MYAGE e) 67temp f) TeMpOrArY_VaLu_E

2. What is displayed by each of the following statements?


var value1 = 36, value = 15;
document.write("value1 + value2");
document.write("<P>");
document.write("value1" + value2);
document.write("<P>");
document.write(value1 + "value2");
document.write("<P>");
document.write(value1 + value2);

3. Rewrite the following using just one instruction:

document.write("The answer to the calculation is ");


document.write(answer);
document.write(".");
document.write("<P>");

(Hint, you can incorporate <P> as part of other strings, or concatenate it to other strings.)

4. Write a full JavaScript program that displays the answers to the following calculations in white text
on a blue background: 141 x 302, 15772 + 3205 and 6000 / 47118.

5. What's wrong with the following program? There are several errors. Correct the program so that it
works properly. What is the number displayed on the screen?

<SCRIPT LANGUAGE="JavaScript"
document.bgcolour = "black";
write(<FONT COLOR=YELLOW>);
first number = 200
2nd_number = -136;
answer = first number * 2n d_number + 400
document write("The answer is " answer.)
<SCRIPT>

6. The following text shows the HTML needed to display a table with three columns. How would you
rewrite this so that the table was displayed using JavaScript only?

<TABLE>
<TR>
<TD>This is the first column</TD>
<TD>Now the second</TD>
<TD>And this is the third</TD>
</TR>
</TABLE>
Questions for JavaScript Lesson 2

1. The following program is riddled with errors. Can you find them and correct them all? When you run
the program, what number should it display?

<SCRIPT LANGUAGE="JavaScript>
x = prompt("Please enter a number");
answer = x % 72
alert("The answer is " answer)
<SCRIPT>

2. Rewrite the following program so that it uses alert() statements:

<SCRIPT>
document.write("There was an old woman ");
document.write("who lived in a shoe.<P>");
document.write("She had so many children, ");
document.write("she didn't know what to do.<P>");
document.write("But then they grew up ");
document.write("and she had no-one to handle.<P>");
document.write("So the old woman moved out ...<P>");
document.write("... and into a sandal!");
</SCRIPT>

3. Write a program that asks for two numbers from the user (which can be whole numbers or decimals!)
and displays the sum (adding the numbers), the difference (subtracting the second number from the
first), the product (multiplying the numbers), the quotient (dividing the first number by the second)
and the remainder of the division that has just been carried out.

4. Write a program which asks the user for a number and then displays the times table for that number
from 1 x to 12 x (i.e. if the user enters the number 7, then the program would display 12 lines, the first
one being 1 x 7 = 7 and the last being 12 x 7 = 84). There is an efficient way of doing this using a
loop, but you're not supposed to know about those yet, so you will have to put in 12 display
statements.

5. What is the value displayed by the following program?

<SCRIPT LANGUAGE="JavaScript">
var x = 2;
// x = 7;
alert(x);
</SCRIPT>
Exercises on the if and switch statements

With each one of the following tasks, you should write JavaScript programs embedded inside HTML files
which test your solutions:

1. Write a program which asks the user for a number between 0 and 100. The program should display
one of three messages depending on the value of the number: "Too small", "In range" or "Too large".

2. This program should display the message "That is correct" if the variable a is either 3 or 4. However,
it contains several errors. What should the program look like?

<SCRIPT LANGUAGE="JavaScript">
var a = prompt("Enter a number","");
if (a = 3 && a = 4;
{ document.write("That is correct<P>");
}
</SCRIPT>

3. Look at the following program:

<SCRIPT LANGUAGE="JavaScript">
var first = "Hello", second = "Goodbye";
var number = 32;
if (first != "Hello" && second == "Goodbye")
{ number += 12;
number *= 2;
}
else
{ number -= 10;
}
if (first == "Hello" || second != "Goodbye")
{ number = 13;
}
else
{ number *= 5;
}
alert("The value of number is " + number + "<P>");
</SCRIPT>

What value is displayed on the screen? Don't forget to type the program on the computer to check
your answer!

4. Write a program which asks the user to enter the three side lengths of a triangle, one at a time. The
program should then check to see if the numbers entered form the sides of a valid triangle.
Remember, any two sides of a triangle must add to give a number larger than the third side, and that
no side of the triangle can be less than zero. If the program finds a problem with the numbers entered,
it should report it to the user. On the other hand, if there is no problem, the program should display
the perimeter of the triangle.
5. Write a program that asks the user for a number between 1 and 10. If a suitable number is entered,
then the program uses a switch statement to display a message for that number. For instance, if the
user enters 3, the program might display "Three blind mice". If the user enters 7, the program might
say "Seven days in a week." etc.

JavaScript Loops - Homework Questions

1. Take the example program that displays all the times tables starting from 1 x 1 = 1 and going up to
12 x 12 = 144 and rewrite it so that it only uses do-while loops.

2. The following loop should terminate when the user enters a number which is either less than 10 or
greater than 20. However, it contains a few errors. What is the error and how should the program be
rewritten?

<SCRIPT LANGUAGE="JavaScript">
var number;
var s = prompt("Please enter a number outside the range 10 to
20","");
while s > 10 || s < 20
{ number = parseFloat(s);
}
document.write("You entered the value " + number + ".<P>");
</SCRIPT>

3. Write a program that displays a table containing 10 rows and 10 columns on the screen, with each cell
containing the letter X. You will recall that in HTML a table is enclosed within <TABLE> and
</TABLE> tags, that each row within that table is enclosed within <TR> and </TR> tags, and that
each cell within that row is enclosed within <TD> and </TD> tags.

4. The average of a series of number is found by adding the numbers together and dividing by how many
numbers there are (so the average of 2, 5, 1 and 7 is equal to (2 + 5 + 1 + 7) / 4 = 15 / 4 = 3.75). Write
a program which asks the user for a series of numbers, to be entered one at a time, and calculates their
sum, their average, the smallest value entered and the largest value entered.

5. Write a program which gets the user to enter the digits of a number one at a time (e.g. 7 followed by 3
followed by 4) and then constructs the number from them (e.g. 734). The program wouldn't know in
advance how many digits there were going to be, so the program would have to indicate a particular
stopping condition which the user can enter to indicate that there are no more digits to come.

Those of you who are familiar with the binary system might like to adapt the program so that the user
can enter the digits of a binary number one at a time, and the program will display the equivalent base
number.

6. Mathematics contains a special function called factorial, which is defined as follows:


0! and 1! (called "zero factorial" and "one factorial" respectively) are both defined as being 1.
2! ("two factorial") = 2 x 1 = 2
3! ("three factorial") = 3 x 2 x 1 = 6
4! = 4 x 3 x 2 x 1 = 24
5! = 5 x 4 x 3 x 2 x 1 = 120 etc.
Write a program which asks the user for a positive whole number and calculates the factorial of it.
Beware, though! Factorial numbers quickly become very large - for instance, 10! is well over a
million!

7. The first train to London from my local train station arrives promptly at 5.33 in the morning and then
regularly every 19 minutes after that. However, the service stops fairly early: anyone arriving at the
station after 10 p.m. has missed the last train.
a) Write a program which displays the times of all the trains to London.
b) Adapt the program so that it also counts the number of trains to London.
c) The journey to London takes exactly 34 minutes. Adapt the program so that it also gives the arrival
times of all the trains.

JavaScript, Lesson 5 - Homework Questions

1. Write a program that creates an array with four rows and four columns, and then asks the user to enter
values for all the elements. The program should then "rotate" the array clockwise, as shown in this
example:
4 11 6 3 9 3 7 4
7 2 4 0 6 1 2 11
3 1 8 0 8 8 4 6
9 6 8 1 1 0 0 3

2. Twelve children (Jim, Sandra, Freddie, Richard, Diane, Mary, Natalie, Jeremy, Henry, William, Sarah
and Charles) are to sit at desks in a rectangular arrangement (3 rows of 4 columns of desks). However,
William and Jim must sit in the front row (nearest the teacher) because they tend to mess around in
class. Sarah must not sit next to Diane as they tend to copy each others' work. Henry must not sit
adjacent to (within one space of in any direction) Freddie or Natalie and Sandra and Jim must not be
in the same row.
Write a program which asks for a seating plan from the user and checks to make sure it meets those
restrictions. The program should then display the seating plan.

3. Write a computer program that allows two human players to play noughts-and-crosses (tic-tac-toe)
against each other. The program should detect when either player has won, or when the game is a
draw. The board position can be displayed in terms of words (as at the moment you probably don't
know how to draw the board in terms of pictures yet).

4. Create a three-dimensional array which represents a section of the galaxy. Your array should have 10
rows, 10 columns and 10 layers. The star ship Enterprise is at position (1, 3, 4), a Klingon battleship
at (7, 9, 7) and stars at (1, 3, 9), (4, 2, 7), (2, 7, 3), (8, 5, 6) and (7, 2, 5).
a) How would you display this information on the screen (which can only represent two dimensions)?
b) Add lines to your program which allows the captain of the Enterprise to plot a course to intercept
the Klingons, and which informs him if the course will take him through a star.

5. A magic square is a square grid full of numbers where each row, each column and each of the two
diagonals adds to the same number. For instance, a 3-by-3 magic square containing the numbers 1, 2,
3 etc. up to 9 will have rows, columns and diagonals where the numbers add to give 15. Write a
program which allows the user to enter the numbers, and then reports whether the array forms a magic
square. More importantly, the user should be able to alter the numbers in the array, with the program
reporting the sums of the rows, columns and diagonals, and then print a congratulatory message when
the array finally is a magic square.

6. A prime number is one which can only be divided by two whole numbers - 1 and itself. Hence 7 is a
prime number because the only whole numbers that divide into it are 1 and 7. On the other hand 8 is
not a prime number because it also divides by 2 and 4. The first prime number is 2, not 1!

The ancient Greek mathematician Eratosthenes developed this method for finding all the prime
numbers up to a certain limit (say 100):
• You start with an array of numbers, from 2 to 100.
• You then report the first of those numbers (which is 2) as the first prime number.
• Then remove all multiples of 2 from the list (i.e. 2 itself, 4, 6, 8 etc. up to 100) by setting
those entries in the array to -1 (meaning "this number is defunct!")
• Then find the first non-defunct number in the array (which will be 3), report it as a prime
and remove all its multiples by setting the corresponding elements to -1.
• Repeat the process until all the numbers in the array are defunct.

Write a program that allows the user to enter an upper limit (it needn't be 100) and then displays all
the prime numbers up to that limit using this "Sieve of Eratosthenes".

JavaScript, Lesson 6 - Homework

1. Here is a program that defines and calls a function. However, the program is full of errors. Please
correct all the errors:

<SCRIPT LANGUAGE=JavaScript">
function my Function ();
var x;
x = 2;
document.write("The value of x is " + x);
};

document.write("Here I call the function : " + myfunction)


<\SCRIPT>

2. In the following program, what number is displayed on the screen?

<SCRIPT LANGUAGE="JavaScript">
alert(func(func(2,3),func(3,2)));

function func (x, y)


{ return 10 * x + y;
}
</SCRIPT>

3. Write a function which takes three parameters, called first, second and third, and which
returns the largest of the three parameters.

4. Look at this program:


<SCRIPT LANGUAGE="JavaScript">
function multiply (x, y)
{ return x * y;
}

var y = 12.44, x = 9.315;


document.write(multiply(y, x));
</SCRIPT>

• What are the values of x and y before the function is called?


• What are the values of x and y inside the function?
• What is the value displayed by the program?

5. Write three functions, add to add the its two parameters together and return the sum, multiply to
multiply its two parameters, and square to multiply its single parameter by itself (i.e. if the parameter
were 3, the result would be 9, if it were 7, the result would be 49 etc.)

Use your functions to calculate the result of this mathematical expression, which should be calculated
using four function calls:
(3*4 + 5*7)²

JavaScript, Lesson 7 - Homework

1. The following diagram shows a form which asks the user for certain details. The symbol (*) indicates
an entry which must be completed (i.e. the program processing the form should refuse to accept a
form where any of these fields is blank). Recreate this form using HTML and connect it to a program
which checks to ensure that the required fields contain some sort of data. (You may want to use a
table to line the elements of the form correctly).

2. Write a program that implements a form containing two text elements and a button. When the user has
entered some text in both elements, clicking on the button will swap the two pieces of text. If either of
the text elements is empty then clicking on the button should produce an error message.
3. You have already seen that the document.write() method can be used to write HTML tags on
the screen. Use this method to get a JavaScript program to create a form on the screen, together with
its own JavaScript event handler! (The form doesn't have to be a very complicated one!)

4. Create a web page that consists of a hyperlink, whose caption is "Please do not click on this link".
When the user clicks on the link (as will inevitably happen!) the web page should display the message
"I told you not to click on the link!"

5. In section 3, you were asked to write a program that asked the user for the three sides of a triangle and
then displayed its perimeter. Rewrite that program so that it uses text elements rather than the
prompt() instruction.

6. Write a simple quiz program that asks the user 10 general knowledge questions (such as "What is the
capital of France?") using forms and a button at the end to submit the answers. Clicking on the
answers displays a score at the end.

JavaScript Lesson 8 (Dates and Timers) - Homework

1. Write a program which displays the full date and time, and then displays the (updated) date and time
exactly 5 minutes later.

2. What should be displayed by this program? <SCRIPT LANGUAGE="JavaScript">


var dte = new Date("4 June 2001");
var d = dte.getDate();
var m = dte.getMonth();
var y = dte.getFullYear();
dte.setFullYear(y + 150);
dte.setMonth(m + 150);
dte.setDate(d + 150);
document.write(dte);
</SCRIPT>

3. Write a program which allows you to enter a reminder message and a time delay (say 10 minutes).
The program should display the message in an alert box after the specified delay. Does the message
still appear even if you have left that particular web page and started browsing on the Internet?

4. The following two programs don't produce the same result - or do they?

<SCRIPT LANGUAGE="JavaScript"> <SCRIPT LANGUAGE="JavaScript">


var d = new Date(); var d = new Date();
var x = d.getMonth(); d.setMonth(d.getMonth() + 400);
var y = g.getDate(); d.setDate(d.getDate() + 150);
d.setMonth(x + 400); alert(d);
d.setDate(y + 150); </SCRIPT>
alert(d);
</SCRIPT>

5. How many minutes seconds have elapsed since the start of the new century? (You may decide
whether this is midnight on the 1st of January 2000, or midnight on the first of January 2001.) How
many days old are you?

6. Write a program which tells you on which day of the week Christmas Day (25th December) will fall
each year from now until 2099.

7. Write a program that invites the user to estimate one minute of time. The user should click on a button
on the screen, and then click on the button again after what he/she estimates to be one minute. The
program then displays the true length of time. If the user still hasn't clicked on the button after 5
minutes have elapsed, the program should display a "Ah! Come on!" message.

8. Create an electronic stopwatch program which allows a user to click on a button to start the stopwatch
and then click on the same button to stop it again. The stopwatch should then inform the user how
much time has elapsed between the two button clicks - both in milliseconds, and also in seconds and
minutes.

9. How many days have elapsed since


a) the death of Beethoven, on the 23rd March 1827?
b) the dropping of the atom bomb on 6th August 1945?
On which days of the week did each of these events happen?

JavaScript Lesson 9, Homework questions

1. Create a program that contains two images, such that when the mouse pointer moves over either of the
two images, they swap round.

2. The following diagram shows a cartoon character walking across the screen. Create a program
containing a one-dimensional table, with several table divisions (using the <TD> tag) in it, and use it
to make a picture move across the screen.

3. Write a menu program that allows the user to select from a range of web sites by clicking on a picture.
The access to the web sites themselves should be through a single hyperlink, which is assigned to
different addresses by the menu options.

4. Here is a hyperlink containing a picture:

<A HREF="http://www.mysite.com"><IMG SRC="pic.gif"></A>

How would you rewrite this so that it didn't need to use a <A> tag at all?

5. How would you describe the effect of the following instructions in English?
a) document.go(-6);
b) document.go(3);

If you activate a web page "from scratch" (i.e. not via another link), and it executes a JavaScript
program containing the instructions that you see above, what effect do they have then?

6. Write a simple noughts-and-crosses game (tic-tac-toe) that allows two players to place either a cross
or a nought as appropriate inside a table with 3 rows and 3 columns. The program should detect when
one of the players has won, but need not be any more complicated than that (i.e. there is not need to
implement a function to let the computer play against a human opponent - unless you want to!)

7. Is it possible to get the cells of a table to change colour when you click on them. In fact, it is fairly
easy - if those cells contain images which completely fill them. The images would have to be
rectangular "slabs" of colour, and clicking on them would cause the source of the image to change to
another rectangular slab of colour. How would you go about implementing this?

8. As well as having a src property, the elements of the array document.images[] have a width
and a height property, which specify the width and height of the image in pixels (screen dots). For
instance, the following command ensures that the first picture on the screen is exactly 120 pixels wide
(about one eighth of the screen width, typically):

document.images[0].width = 120;

Write a program which displays the same image 5 times, starting with a width of 20 pixels and
doubling in width for each subsequent image.

Lesson 10, String Manipulation, Homework Questions

1. Given the following two program instructions:

var s1 = "The owl and the pussy cat", s2 = "Hickory Dickory Dock";
var s3 = s1 + s2;

What is returned by each of the following method calls?

s3.substring(10, 20) s1.indexOf("pussy")


s3.substring(15, 50) s2.indexOf("Dockery")
s1.substring(17) s3.indexOf(" ",30)
s2.charAt(12) s3.charAt(s2.length)
s3.length s1.charAt(23 - s1.length % 7)

2. What's wrong with the following statement? How would you correct the error without changing the
contents of the string?

a = "The answer was "six" not "seven", you idiot!";

3. Suppose you had the following two commands, operating on a string variable passage, and
following directly on from one another:
passage = passage.replace("a","b");
passage = passage.replace("b","a");

The second statement appears to undo the effect of the first, so if there are no intervening instructions,
they should cancel each other out. Is this the case, or is it possible that the variable passage is not
returned to its initial condition?

4. Write a program which asks the user for a piece of text as an input and a word to be blanked out with
*** signs. It should then display the text with all occurrences of the word blanked out.

5. The split() method can be used to split a sentence into words by recognising the space as a word
separator. What happens if you give it a string which contains two or more spaces next to each other?
Does it treat those spaces as surrounding words which contain no characters (i.e. words of 0 length),
or does it recognise that more than one space can be used as a separator between words? Write a
program that will test this idea.

6. A palindrome is a word or phrase which is the same when spelled backwards, such as the words
"level" or "deified". Write a program which asks the user for an input and then informs the user
whether that input is a palindrome or not. You may find that the best way to do it is using the
charAt() method.

7. Caesar put all his messages into code as follows: He replaced all the letter As in the plain message
with Cs in the coded one, all the letter Bs in the plain message with Ds in the coded one, Cs in the
plain message with Es in the coded one etc. All the letter Ys in the plain message were replaced by As
in the coded message, and all the letter Zs in the plain message were replaced by As in the coded one.

Write a program which takes a plain English message, encodes it using Caesar's cipher, and then
displays it on the screen. For good measure, you should write another program which takes messages
coded in this way and produces the plain English version.

8. Write a program which counts the vowels in a piece of text.

JavaScript Lesson 11, Regular Expressions, Homework Questions

1. Write a program which prompts the user to enter text into a text area, then searches that text for all
four-letter words, and replaces them with ****. It should only alter four-letter words, not words with
more than four letters.

2. Assuming that the string s has been set to Had we had haddock for tea, we would
have had enough! what is returned by each of the following method calls?

s.match(/had/); s.match(/had\b/); s.replace(/\shad\s/,”x”);


s.match(/had/g); s.match(/had\b/g); s.replace(/\shad/,”x”);
s.match(/had/i); s.replace(/had/g,”Did”); s.match(/\shad\s/);
s.match(/had/gi); s.replace(/\$had/i,”Did”); s.match(/\bhad\b/);

3. If we want to find the word computer inside a text string, it wouldn’t be a good idea to use the
regular expression /\scomputer\s/ Why not? How should the regular expression be rewritten to
make it fool-proof? What should the regular expression be if you wanted it to match the words
computer and computers but no other word?

4. In Slobovia, all the telephone numbers take the form of a 0 followed by a # symbol, followed by 3
digits, another # symbol and another four digits. All car licence plates take the form of a letter of the
alphabet (which can be upper or lower case), three digits, then a single space followed by three more
letters of the alphabet (again, upper or lower case). Write two regular expressions, one for matching
Slobovian telephone numbers, the other for matching Slobovian car licence plate numbers. The
regular expressions should only match substrings which are correctly formulated according to the
rules above.

5. Each of the following regular expressions can be written in a more efficient way. How could they be
rewritten?

/[abcde]/ /[^0427691035]/ /[^\w]/


/[0123456789]/ /\w\w\w\w\w\w\w\w\w/ /[^\D]/

6. Some web browsers (very old ones) cannot cope with JavaScript, so all JavaScript instructions
between <SCRIPT> (or <SCRIPT LANGUAGE=”JavaScript”>) and </SCRIPT> tags must be
removed, including the <SCRIPT> and </SCRIPT> tags themselves. Write a program which takes
the contents of a text area, which we may assume to be the HTML for a web page, and removes all the
JavaScript code as specified. You needn’t worry about how the code gets into the text area – it could
always be placed there by the user, via Copy and Paste.

7. The regular expression /\$\$/ only matches one thing. What is that thing?

8. Some web browsers cannot cope with colour names in tags such as <FONT>, preferring hexadecimal
character codes, such as #FF0000 (for RED), #00FF00 (for GREEN) and #0000FF (for BLUE), for
example. Write a program similar to the one in question 6 that searches for such tags and replaces the
colour name with the hexadecimal code. Remember, the patterns that you are looking for are basically
COLOR=RED (where RED, of course, can be any colour name), except that there may be any number
of spaces or new line characters both before and after the equals sign. You might like to adapt the
program so that it can pick up other references to colours, such as LINK=BLUE (in the <BODY> tag)
or BGCOLOR=YELLOW (in the <BODY> tag or as a background for table divisions).

9. Is it possible to use a regular expression to split a string into an array elements, i.e. is it possible to
pass a regular expression as the parameter to the split() method of a string?

S-ar putea să vă placă și