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
上一篇:SVG系列一


下一篇:Zabbix agent自动注册功能实现主机批量监控