Java Reference
In-Depth Information
return result;
}
var doubledNumbers = numbers.map(doubleAndAlert);
alert(“The doubled numbers are: “ + doubledNumbers);
Figure 5-3 shows the results of this code. You can see that there is very little difference between this code
and the code for the forEach() method. The doubleAndAlert() function now returns the product of
the element's value and 2 (instead of outputting it in an alert box), and you show the user the full result
set after calling the map() method.
Figure 5-3
As you can see, these seven methods can come in handy when you need to fi nd elements in an array, or
you want to perform the same operation on all elements.
The only downside to these methods is that they are not supported in Internet Explorer, and Microsoft
has not yet indicated if or when they will be added. One thing is for sure, though: Our jobs as developers
will become much easier the day Microsoft does add support for them.
The Math Object
The Math object provides a number of useful mathematical functions and number manipulation meth-
ods. You'll be taking a look at some of them here, but you'll fi nd the rest described in detail at the W3C
site: www.w3schools.com/jsref/default.asp .
The Math object is a little unusual in that JavaScript automatically creates it for you. There's no need to
declare a variable as a Math object or defi ne a new Math object before being able to use it, making it a
little bit easier to use.
The properties of the Math object include some useful math constants, such as the PI property (giving
the value 3.14159 and so on). You access these properties, as usual, by placing a dot after the object
name ( Math ) and then writing the property name. For example, to calculate the area of a circle, you may
use the following code:
var radius = prompt(“Give the radius of the circle”, “”);
var area = Math.PI * radius * radius;
document.write(“The area is “ + area);
The methods of the Math object include some operations that are impossible, or complex, to perform
using the standard mathematical operators (+, -, *, and /). For example, the cos() method returns the
cosine of the value passed as a parameter. You'll look at a few of these methods now.
Search WWH ::




Custom Search