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.