JavaScript 中的forEach、map、reduce 、filter、every和some

js
创建时间:2021-12-25 23:06:43

目录

copy

JavaScript 中的foreach、map、reduce 、filter、every和some

其他笔记

forEach

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

  1. 返回值为undefined
  2. 已删除或者未初始化的项将被跳过
  3. 被调用时,不会改变原数组
  4. promise 或 async 函数做callback,需要考虑执行顺序影响

map

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

  1. 返回值是一个由原数组每个元素执行回调函数的结果组成的新数组。
  2. 不修改调用它的原数组本身

reduce

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

reducer callback接收4个参数:

  1. Accumulator (acc) (累计器)
  2. Current Value (cur) (当前值)
  3. Current Index (idx) (当前索引)
  4. Source Array (src) (源数组)

initialValue 作为第一次调用 callback函数时的第一个参数的值。

  1. initialValue 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。
  2. 返回的是函数累计处理的结果
  3. 如果没有提供initialValue,reduce 会从索引1的地方开始执行 callback 方法,跳过第一个索引。如果提供initialValue,从索引0开始。
  4. 不包括数组中被删除或从未被赋值的元素

filter

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

  1. 一个新的、由通过测试的元素组成的数组,如果没有任何数组元素通过测试,则返回空数组。
  2. 不会改变原数组,它返回过滤后的新数组
  3. 只会在已经赋值的索引上被调用

every

arr.every(callback(element[, index[, array]])[, thisArg])

  1. 如果回调函数的每一次返回都为 truthy 值,返回 true ,否则返回 false。
  2. 不会改变原数组。
  3. 只会在被赋值的索引上被调用

some

arr.some(callback(element[, index[, array]])[, thisArg])

  1. 数组中有至少一个元素通过回调函数的测试就会返回true;所有元素都没有通过回调函数的测试返回值才会为false
  2. 被调用时不会改变数组。
  3. 只会在有值的索引上被调用

参考

如何形象地解释 JavaScript 中 map、foreach、reduce 间的区别?

Array