es6 数组方法

map    映射   一对一

  • map()不会对空数组进行检测
  • map()不会改变原始数组

参数说明:

  • function(currentValue, index, arr)必须。为一个函数,数组中的每个元素都会执行这个函数。其中函数参数:
  1. currentValue必须。当前元素的的值。
  2. index可选。当前元素的索引。
  3. 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

  1. reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
  2. reduce() 可以作为一个高阶函数,用于函数的 compose
  3. reduce() 对于空数组是不会执行回调函数的
array.reduce(function(prev, current, currentIndex, arr), initialValue)
  1. prev:函数传进来的初始值或上一次回调的返回值
  2. current:数组中当前处理的元素值
  3. currentIndex:当前元素索引
  4. arr:当前元素所属的数组本身
  5. 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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值