switch (place) {
case 1: place += "st"; break;
case 2: place += "nd"; break;
case 3: place += "rd"; break;
default: place += "th";
}
document.write("You have won " + place + " place!");
In this version, the switch statement terminates correctly as soon as the sux “nd”
has bee n ap pended. Of c ourse, break doesn’t change the flow of the statements
outside of swit ch. When the switch statement in our example terminate s—either
regularly or through a premature exit caused by one o f the break statements—the
document.write() is always executed after it.
Mike: Don’t we need braces to make a compound statement after case keywords?
Professor: No, we don’t. You can place as many statements following each c ase
keyword as you like. They will all be executed until either switch ends or break is
encountered.
Maria: I think our progr am still doesn’t work p roperly. What about values above 2 0?
The program will produce “21th” instead of the correct “21st, and “22th” instead of
“22nd , and so on.
Professor: You’re right a gain. This pattern actually repeats every 10 numbers, except
for 11, 12, 13, 11 1, 112, 113, and so on. T here are of course more solutions and this
is one of them:
switch (place % 100 <= 20 ? place % 20 : place % 10) {
case 1: ...
8.3 Math Object
Professor: I think it’s about time we started moving to a higher level of programmin g.
You learned quite a bit about primitive data types and how to manipulate them using
operators and some basic co ntrol statements. However, as your programs become
more com plex, you will soon need to organize data a nd code more eciently in order
for y our projects to stay under control. The concept of objects oers you one aspect
of such data and code organization. Essentially, objects group d ata and code that
logically fit together and hide unnecessary implemen ta tion details from other pa rts of
a program. In object-oriented terminology, data and code that are integrated in an
object are called properties and methods, respectively. Properties define the state of
an object, while methods define its behavior.
You can think of an object in the same way as you think of a real-world object. For
example, your mobile is quite a complex device, yet yo u don’t have to be a rocket
scientist to be able to use it because its actu al implementation is hidden from you.
There’s quite some data stored inside your mobile. Apart from the most obvious
contacts, th ere is a lso information like whether Bluetooth
r
is on or o, or whether
152 Meeting 8. Introducing Objects
hiding your identity is enabled. These are all properties of your mobile. There are
also certain things you can do with your mobile. Yo u can, for example, take a ph oto,
listen to your favorite music, or even make a call. These a re methods of your mo bile.
Mike: Am I thinking righ t if I see properties as variables and methods as functions?
Professor: You couldn’t be more right about that. As a matter of fact, properties are
sometimes also referred to a s member variables or member data, and methods are
called member functions. They are also known under a common name, members.
By the way, everything in JavaScript is an object. E ven primitive data ty pes have their
object counterparts.
It can happen that mathematics isn’t pr ecisely you r c up of tea, but sooner or later you
discover that you can ’t do without it. That’s wh y JavaScript has a built-in object called
Math. In section E.12 on page 409 at the end of this book you will find m ore details
about all that this object has in store for you. When you understand the principles, you
will know how to use it.
The Math object has a set of properties. For example:
Math.E //Base of the natural logarithm, approximately 2.71828
//(Euler’s number).
Math.PI //Ratio of the circumference of a circle to its diameter,
//approximately 3.14159.
Notice a dot (.) following the name of the object. This is an operator used to access
properties of an objec t. You can think of PI as a variable being integrated inside the
Math object. When you want to acc ess it, yo u first name the object followed by a dot
access o perator, and then PI.
Maria: If PI is a variable, can I change its value?
Professor: No, you can’t. That’s out of the scope of our course, but p roperties of
JavaScript objects have certain attributes attached to them . Specifically, the PI prop-
erty has the writable attribute set to false. Just think of Math.PI as a constant, or
a variable whose value you cannot change. You can use it freely in all othe r situations,
though. For example, you can compute the circumference of a circle:
circ = 2 * Math.PI * radius;
Alternatively, you can access a property o f a n object using square brackets ([ ]) and
the property name in string form:
Math["PI"]
An advantage of using square brackets is that you can use any string as a property
name and not just a valid JavaScript identifier.
8.3. M ath Object 153
A much more important advantage is that you can store the name of a p roperty in
a variable and use it w ith a square brac ket property access oper ator, something you
cannot do using a dot operator. For example:
var what = prompt("What do you want to know?");
document.write(Math[what]);
If you enter PI, for example, then you g et the number 3.141592653589793 written in
the browser window.
The Math object has also many useful methods. These are some examples:
Math.abs(x) //Returns the absolute value of x
Math.ceil(x) //Returns the smallest integer greater than or equal
//to x.
Math.floor(x) //Returns the largest integer less than or equal
//to x.
Math.round(x) //Returns the value of x rounded to the nearest
//integer.
Math.cos(x) //Returns the cosine of x.
Math.sin(x) //Returns the sine of x.
Math.pow(x, y) //Returns x to the power of y.
Math.sqrt(x) //Returns the square root of x.
Math.random() //Returns a pseudo-random number between zero
//(inclusive) and one (exclusive).
Professor: Note that none of the above expressions have any side eects. They just
compute and return values.
Mike: E xcuse me, but I don’t see any a dvantage in using objects. What’s the use of
writing Math.PI or Math.abs() when we could simply write shorter PI or abs()
and get the same results?
Professor: I see your point. At this stage it rea lly doesn’t make much sen se. You’ll
just h ave to wait until you learn more about objects so you can appreciate them.
If you feel like gambling, maybe now is your chance. We’re going to program a lucky
lottery number generator.1 There are a zillion lottery rules across the globe and one
of the simplest to program is the one where you must select n dierent numbers from
the range of numbers from one to N. For example, in Lotto Texas
r
, you select six
numbers from one to 54.
So the problem before us is to draw six dier ent rand om numbers out of the range of
numbers from one to 54. Any idea how to do this in a prog ram?
Maria: Basically we repeat something six times. L ike this:
1If you are a gambling addict, then this is not an example for you. You can read further, but you do so
at your own risk.
154 Meeting 8. Introducing Objects
var n = 7;
while (n--) {
//Do something 6 times
}
Professor: You’re close. But what’s wr ong?
Mike: If I remem ber c orrectly, n is decremented after its value is returned. That means
that when n is one, it is first evaluated as a truthy value and only then decremented to
zero. As a consequence , the loop bod y is executed once more. I think that n end s up
with the value of -1 when the loop finishes. The loop there fore runs seven iterations.
Professor: Not bad at all. You’ve obviously done your homework. Now we have to
find out what we need to repeat.
Maria: We need random numbers. The Math.r andom() function could do the trick
but th e rang e is not right.
Professor: That means we have some extra work to do.
Mike: We can multiply whatever Math.random() retu rns by 54 and rou nd the result.
Maria: That way you’ll get 55 and not 54 possible numbers.
Professor: You are a sharp observer, congratulations! If you multiply the ran ge from
zero to one by 54 and then round a number to the nearest integer, then you can get
integers from zero to 54 inclusive, which is all together 55 dierent numbers.
Before we write a final solution, I would like to say some words about the random()
method. Each time the function is called, it returns a pseudo-ra ndom real number
greater than or equa l to zer o and less than one. It is very important that one can never
appear as the function’s retur n value.
Maria: Why did you say “pseudo- random”?
Professor: Because the returned numbers only app ear to be random. The numbers
returned by the random() method have statistical properties of r andom numbers, but
they are generated by a deterministic algorithm. They are not truly r andom as, for
example, th e roll of a dice, but for many practical applications they are all right. This
is an interesting topic but, unfortunately, we do n ot have time to explore it in more
detail.
Putting it all together, we come up with the following possible solution:
var x, n = 6;
while (n--) {
x = Math.floor(Math.random() * 54) + 1;
document.write(x + " ");
}
Mike: You said that m ultiplying by 54 will give us 55 possible dierent values.
8.3. M ath Object 155
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.60.167