es6 数组方法

ゞ 浴缸里的玫瑰 2023-06-17 12:55 183阅读 0赞

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) => {

    1. return item * item;

    })

    console.log(newArray) // [1, 4, 9, 16, 25]

forEach 遍历 循环一遍

  1. var a = ['A', 'B', 'C'];
  2. a.forEach(function (element, index, array) {
  3. // element: 指向当前元素的值
  4. // index: 指向当前索引
  5. // array: 指向Array对象本身
  6. alert(element);
  7. });

reduce

  1. reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
  2. reduce() 可以作为一个高阶函数,用于函数的 compose
  3. reduce() 对于空数组是不会执行回调函数的

    array.reduce(function(prev, current, currentIndex, arr), initialValue)

  4. prev:函数传进来的初始值或上一次回调的返回值

  5. current:数组中当前处理的元素值
  6. currentIndex:当前元素索引
  7. arr:当前元素所属的数组本身
  8. initialValue:传给函数的初始值

    const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    1. const sum = arr.reduce(function (prev, current) {
    2. return prev+current
    3. }, 0)
    4. console.log(sum) //55

filter 过滤

filter用于对数组进行过滤
它创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

其中,函数 function 为必须,数组中的每个元素都会执行这个函数。且如果返回值为 true,则该元素被保留;
函数的第一个参数 currentValue 也为必须,代表当前元素的值。

  1. Array.filter(function(currentValue, indedx, arr), thisValue)
  2. let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  3. let res = nums.filter((num) => {
  4. return num > 5;
  5. });
  6. console.log(res); // [6, 7, 8, 9, 10]

发表评论

表情:
评论列表 (有 0 条评论,183人围观)

还没有评论,来说两句吧...

相关阅读

    相关 es6数组方法图解

    最近接触了一些 web前端开发人员,发现还是很多人不适用es6 提供的语义化api。 下面分享下看到的图解 es6 数组方法。 很形象的es6数组方法解释: ![请添