Array陣列(JS)之map與reduce方法
阿新 • • 發佈:2019-01-04
map
// Define the callback function.
const AreaOfCircle = (radius) => {
let area = Math.PI * (radius * radius);
return area.toFixed(0);
}
// Create an array.
const radii = [10, 20, 30];
// Get the areas from the radii.
let areas = radii.map(AreaOfCircle);
document.write(areas);
// Output:
// 314,1257,2827
reduce
// Define the callback function.
const appendCurrent = (previousValue, currentValue) => {
return previousValue + "::" + currentValue;
}
// Create an array.
const elements = ["abc", "def", 123, 456];
// Call the reduce method, which calls the callback function
// for each array element.
let result = elements.reduce(appendCurrent);
document.write(result);
// Output:
// abc::def::123::456