js 数组 map,filter,reduce

原文链接: js 数组 map,filter,reduce

上一篇: vis 和黄色边框斗智斗勇

下一篇: js es6 对象解构

filter

过滤器,按照一定条件,过滤数组中的元素

  选择数组中值大于3的组合为新数组
  a.filter((item) => item > 3)

Syntax

var newArray = arr.filter(callback[, thisArg])

Parameters

callback

Function is a predicate, to test each element of the array. Return true to keep the element, false otherwise, taking three arguments:

element

The current element being processed in the array.

index Optional

The index of the current element being processed in the array.

array Optional

The array filter was called upon.

thisArg Optional

Optional. Value to use as this when executing callback .

map

映射,将数组中的元素,按照一定的规则映射为新数组

新数组中的元素是a中的数的平方
a.map(
    (item) => item * item
  )

Syntax

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])

Parameters

callback

Function that produces an element of the new Array, taking three arguments:

currentValue

The current element being processed in the array.

index Optional

The index of the current element being processed in the array.

array Optional

The array map was called upon.

thisArg Optional

Value to use as this when executing callback .

reduce

聚合,将数组按照一定的方式,聚合为一个结果,这个结果不仅仅只是一个数,可以是对象或数组!!!

对a中的数字求和
a.reduce(
    (pre, cur) => pre += cur,
    0
  )

将a中的数字连接成字符串
a.reduce(
    (pre, cur) => pre += cur,
    ''
  )

对于a中的元素,如果该元素的平方比4大,则将该数的平方放入新数组
只使用map或filter是做不到的
a.reduce(
    (pre, cur) => {
      let ret = cur * cur
      if (ret > 4)
        pre.push(ret)
      return pre
    },
    []
  )
统计a中每个数字出现的次数,返回一个对象
对象的键是a中的数字种类,值是该数出现的次数
a.reduce(
    (pre, cur) => {
      pre[cur] = pre[cur] ? ++pre[cur] : 1
      return pre
    },
    {}
  )

同样的功能,使用逗号表达式和三元表达式简化箭头函数
 a.reduce(
    (pre, cur) => (pre[cur] ? pre[cur]++ : pre[cur] = 1, pre),
    {}
  )

Syntax

arr.reduce(callback[, initialValue])

Parameters

callback

Function to execute on each element in the array, taking four arguments:

accumulator

The accumulator accumulates the callback's return values; it is the accumulated value previously returned in the last invocation of the callback, or initialValue , if supplied (see below).

currentValue

The current element being processed in the array.

currentIndex Optional

The index of the current element being processed in the array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise.

array Optional

The array reduce() was called upon.

initialValue Optional

Value to use as the first argument to the first call of the callback . If no initial value is supplied, the first element in the array will be used. Calling reduce() on an empty array without an initial value is an error.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值