_.mean(array)
Array _. Mean
2023-09-11 14:15:01 时间
179
_.mean(array)
_.mean计算一个数组的平均值
参数
array (Array): 需要迭代计算平均值的数组
返回值
(number): 返回数组的平均值
例子
_.mean([4, 2, 8, 6]); // => 5
源代码
import baseMean from './meanBy.js' /** * Computes the mean of the values in `array`. * * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the mean. * @example * * mean([4, 2, 8, 6]) * // => 5 */ //计算一个数组的平均值 function mean(array) { return baseMean(array, (value) => value) } export default mean
meanBy
import baseSum from './.internal/baseSum.js' /** Used as references for various `Number` constants. */ const NAN = 0 / 0 /** * This method is like `mean` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be averaged. * The iteratee is invoked with one argument: (value). * * @since 4.7.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per element. * @returns {number} Returns the mean. * @example * * const objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }] * * meanBy(objects, ({ n }) => n) * // => 5 */ //此方法与mean类似,接收一个iteratee为数组中没有给元素调用去生成需要被计算平均值的值 function meanBy(array, iteratee) { const length = array == null ? 0 : array.length//数组长度 return length ? (baseSum(array, iteratee) / length) : NAN //如果数组有元素,调用baseSum计算数组所有元素的和然后除以数组长度计算出平均值,否则返回NaN } export default meanBy
baseSum
/** * The base implementation of `sum` and `sumBy`. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ //sum和sumBy方法的基础实现 function baseSum(array, iteratee) { let result for (const value of array) {//循环数组 const current = iteratee(value)//用iteratee处理当前值 if (current !== undefined) {//如果当前值不是undefined //将当前值加入result中 result = result === undefined ? current : (result + current) } } return result } export default baseSum
相关文章
- PHP中array_map与array_column之间的关系分析
- hive中array嵌套map以及行转列的使用
- C#数组之 []、List、Array、ArrayList应用
- [Algorithm] Reverse array of Chars by word
- [ES2016] Check if an array contains an item using Array.prototype.includes
- (LeetCode 189)Rotate Array
- [Javascript] Filter out Duplicates from Flat JavaScript Array with array.filter / reduce / Set
- [Algorithms] Sort an Array with a Nested for Loop using Insertion Sort in JavaScript
- Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result
- Array对象的方法实现(6)----Array.prototype.indexOf(实现常规参数的功能)
- Index was outside the bounds of the array.
- 关于拷贝常规数组、std::array和std::vector速度的一些测试
- LeetCode 154 Find Minimum in Rotated Sorted Array II
- IndexError: too many indices for array