javascript:数组 array 可调用的几个函数

map() 方法

        将一个数组作为参数,并使用对该数组中每个元素调用提供的函数的结果创建一个新的数组

const numbers = [1, 5, 10, 15];
// The associated function multiply each array number by 2
const doubles = numbers.map(x => x * 2);

console.log(numbers); // [1, 5, 10, 15] (no change)
console.log(doubles); // [2, 10, 20, 30]

filter() 方法

             提供一种针对提供的函数对数组中的每个元素进行过滤的方法,满足这个条件的元素才会添加到数组中。

 

const numbers = [1, 5, 10, 15];
// 添加大于等于 10 的元素
const bigOnes = numbers.filter(x => x >= 10);

console.log(numbers); // [1, 5, 10, 15] (no change)
console.log(bigOnes); // [10, 15]

将 map() 和 filter() 一起使用

// Get titles of movies with an IMDB rating greater or equal to 7.5
const bestTitles = movies => {
  /* Previous code
  const bestTitles = [];
  for (const movie of movies) {
    if (movie.imdbRating >= 7.5) {
      bestTitles.push(movie.title);
    }
  }
  return bestTitles;
  */

  // Filter movies by IMDB rating, then creates a movie titles array
  return movies.filter(movie => movie.imdbRating >= 7.5).map(movie => movie.title);
};
console.log(bestTitles(movieList))

reduce() 方法

        将提供的函数应用于每个数组元素,以将其减少为一个值。这个方法通常用于对数组执行计算。

const numbers = [1, 5, 10, 15];
// 计算数组元素的总和
const sum = numbers.reduce((acc, value) => acc + value, 0);

console.log(numbers); // [1, 5, 10, 15] (no change)
console.log(sum);     // 31

reduece() 方法有几个参数:

  • 第一个是与 reduce() 每个数组元素关联并调用的函数。它有两个参数:第一个是一个累加器,其中包含上次调用函数返回的累积值。另一个函数参数是数组元素。
  • 第二个是累加器的初始值(通常为 0)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值