Array数组(JS)之map与reduce方法

简介: map// Define the callback function.const AreaOfCircle = (radius) => { let area = Math.

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
目录
相关文章
|
2天前
|
JavaScript 前端开发
JavaScript 的数组方法 map()、filter() 和 reduce() 提供了函数式编程处理元素的方式
【5月更文挑战第11天】JavaScript 的数组方法 map()、filter() 和 reduce() 提供了函数式编程处理元素的方式。map() 用于创建新数组,其中元素是原数组元素经过指定函数转换后的结果;filter() 则筛选出通过特定条件的元素生成新数组;reduce() 将数组元素累计为单一值。这三个方法使代码更简洁易读,例如:map() 可用于数组元素乘以 2,filter() 用于选取偶数,reduce() 计算数组元素之和。
8 2
|
2天前
|
JavaScript 前端开发
JavaScript 提供了多种方法来操作 DOM(文档对象模型)
【5月更文挑战第11天】JavaScript 用于DOM操作的方法包括获取元素(getElementById, getElementsByClassName等)、修改内容(innerHTML, innerText, textContent)、改变属性、添加/删除元素(appendChild, removeChild)和调整样式。此外,addEventListener用于监听事件。注意要考虑兼容性和性能当使用这些技术。
6 2
|
3天前
|
JavaScript
通过使用online表单的获取使用,了解vue.js数组的常用操作
通过使用online表单的获取使用,了解vue.js数组的常用操作
|
3天前
|
JavaScript 前端开发
在JavaScript中实现模块化开发有多种方法
JavaScript模块化开发可通过CommonJS、AMD和ES6模块实现。CommonJS适用于服务器端,使用`require`和`module.exports`处理模块;AMD(如RequireJS)用于浏览器端,依赖`require`和`define`;ES6模块提供原生支持,使用`import`和`export`。选择方式需考虑项目环境、复杂度和技术栈。
10 4
|
4天前
|
JavaScript 前端开发
JS tostring()和join()方法
JS tostring()和join()方法
7 1
|
4天前
|
存储 JavaScript 前端开发
深入了解JavaScript中的indexOf()方法:实现数组元素的搜索和索引获取
深入了解JavaScript中的indexOf()方法:实现数组元素的搜索和索引获取
7 0
|
5天前
|
JavaScript 前端开发 索引
js添加、删除、替换、插入元素的方法
js添加、删除、替换、插入元素的方法
10 0
|
6天前
|
JavaScript 前端开发
JavaScript 循环方法详解
JavaScript 循环方法详解
18 1
|
6天前
|
JavaScript 前端开发
JavaScript数字方法详解
JavaScript数字方法详解
17 0
|
6天前
|
存储 JavaScript 前端开发
JavaScript对象方法详解
JavaScript对象方法详解
15 1