1. 程式人生 > >Array陣列(JS)之map與reduce方法

Array陣列(JS)之map與reduce方法

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