函数 map reduce filter
函数 map reduce filter
<script>
var array = [
{
age: 11, name: 'aaa'
},
{
age: 22, name: 'bbb'
},
{
age: 33, name: 'ccc'
}
];
/* map方法接收一个匿名函数为参数,这个匿名函数又有三个参数 参数一:每个item项 参数二:数组的索引 参数三:调用map方法的数组本身,也就是数组array */
var map = array.map(item => item.age);
console.log(map) // [11,22,33]
/* reduce方法 有两个参数 参数一:回调方法 参数二:累计的初始值 计算过程: 0 + 11 = 11 11 + 22 = 33 33 + 33 = 结果 66 循环的是回调方法,数组中的每个成员都进入回调,但区别在于每次回调方法返回的值,都会传递到下次回调中 =》累加求和 */
var reduce = array.reduce((n, item) => n + item.age, 0)
console.log(reduce) // 66
/* filter方法 用于过滤数据 返回一个数组 filter方法接收一个匿名函数,参数就是数组中的item项, 例如:从上面数据中过滤一个name为ccc的数据 只要filter方法的回调函数中的比较运算符的结果为true, 那么符合条件的对象就会被包在一个数组返回,比较结果为false的就被过滤掉了 */
var filter = array.filter(item => item.name === 'ccc')
console.log(filter) // [{age: 33, name: "ccc"}]
</script>
map
如果需要一个数组,使用map()方法
reduce
如果需要一个结果,使用reduce()方法
filter
如果需要过滤出一个结果,使用filter()方法
还没有评论,来说两句吧...