map 映射 一对一
map()
不会对空数组进行检测map()
不会改变原始数组
参数说明:
function(currentValue, index, arr)
:必须。为一个函数,数组中的每个元素都会执行这个函数。其中函数参数:
currentValue
:必须。当前元素的的值。index
:可选。当前元素的索引。arr
:可选。当前元素属于的数组对象。
thisValue
:可选。对象作为该执行回调时使用,传递给函数,用作"this
"的值。
array.map(function(currentValue, index, arr), thisIndex)
let array = [1, 2, 3, 4, 5];
let newArray = array.map((item) => {
return item * item;
})
console.log(newArray) // [1, 4, 9, 16, 25]
forEach 遍历 循环一遍
var a = ['A', 'B', 'C'];
a.forEach(function (element, index, array) {
// element: 指向当前元素的值
// index: 指向当前索引
// array: 指向Array对象本身
alert(element);
});
reduce
- reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
- reduce() 可以作为一个高阶函数,用于函数的 compose
- reduce() 对于空数组是不会执行回调函数的
array.reduce(function(prev, current, currentIndex, arr), initialValue)
- prev:函数传进来的初始值或上一次回调的返回值
- current:数组中当前处理的元素值
- currentIndex:当前元素索引
- arr:当前元素所属的数组本身
- initialValue:传给函数的初始值
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const sum = arr.reduce(function (prev, current) {
return prev+current
}, 0)
console.log(sum) //55
filter 过滤
filter用于对数组进行过滤。
它创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
其中,函数 function 为必须,数组中的每个元素都会执行这个函数。且如果返回值为 true,则该元素被保留;
函数的第一个参数 currentValue 也为必须,代表当前元素的值。
Array.filter(function(currentValue, indedx, arr), thisValue)
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let res = nums.filter((num) => {
return num > 5;
});
console.log(res); // [6, 7, 8, 9, 10]