HTML and CSS Reference
In-Depth Information
Using the map method
The map method enables you to replace values in the array. Every element in the array is
passed to a callback function. The callback function's return value replaces the value for the
position in the array that was passed in. The following example demonstrates having every
number in an array rounded off appropriately:
var money = [12.8, 15.9, 21.7, 35.2];
var roundedMoney = money.map(roundOff, money);
function roundOff(value, position, array) {
return Math.round(value);
}
This example provides the square of a series of numbers:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8];
var squares = numbers.map(squareNumber, numbers);
function squareNumber(value, position, array) {
return value * value;
}
Using the reduce and reduceRight methods
The reduce and reduceRight methods are recursive. Each result of the callback function is
passed back into the callback method as the previous return value along with the current
element to be passed in. This provides some interesting scenarios. The reduce method pro-
cesses the elements of the array in ascending order, whereas the reduceRight processes the
elements of the array in descending order. The following example demonstrates using the
reduce method to calculate a factorial:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var factorials = numbers.reduce(factorial);
function factorial(previous, current) {
return previous * current;
}
In this function, the factorial for 10 is calculated. In the math world, it's denoted as 10!
EXAM TIP
Some advanced functions enable you to change the source array, whereas others don't.
This is an important aspect to keep clear.
You've seen how to use if statements to control program flow. Another concept you can use
to control the flow of JavaScript programs is iterative flow control, which enables you to loop
over a block of code many times. You've already seen some iterative operations when you

Search WWH ::

Custom Search