javascript数组怎么求平均数
时间:2022-09-30 16:00
两种求平均数的方法:1、利用forEach()和length属性来求,语法“function f(v){s+=v;}数组对象.forEach(f);avg=s/数组对象.length;”;2、利用reduce()和length属性来求,语法“function f(p,c){s=p+c;return s;}数组对象.reduce(f);avg=s/数组对象.length;”。
前端(vue)入门到精通课程:进入学习
API 文档、设计、调试、自动化测试一体化协作工具:点击使用
本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
方法1:利用forEach()+length属性
实现思想:
利用forEach()迭代数组计算元素总和
利用length属性计算数组长度
将 数组元素总和 除以 数组长度
实现代码:
- var a = [10, 11, 12], sum = 0,len,avg;
- function f(value) {
- sum += value;
- }
- a.forEach(f);
- console.log("数组元素总和为:"+sum);
- len=a.length;
- console.log("数组长度为:"+len);
- avg=sum/len;
- console.log("数组平均数为:"+avg);
说明:
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
- array.forEach(funtion callbackfn(value, index, array), thisValue)
funtion callbackfn(value, index, array)
:必需参数,指定回调函数,最多可以接收三个参数:
value:数组元素的值。
index:数组元素的数字索引。
array:包含该元素的数组对象。
thisValue
:可省略的参数,回调函数中的 this 可引用的对象。如果省略 thisArg,则 this 的值为 undefined。
方法2:利用reduce()+length属性
实现思想:
利用reduce()迭代数组计算元素总和
利用length属性计算数组长度
将 数组元素总和 除以 数组长度
实现代码:
- var a = [11, 12, 13], sum = 0,len,avg;
- function f(pre,curr) {
- sum=pre+curr;
- return sum;
- }
- a.reduce(f);
- console.log("数组元素总和为:"+sum);
- len=a.length;
- console.log("数组长度为:"+len);
- avg=sum/len;
- console.log("数组平均数为:"+avg);
说明:
reduce() 方法可对数组中的所有元素调用指定的回调函数。该回调函数的返回值为累积结果,并且此返回值在下一次调用该回调函数时作为参数提供。
- array.reduce(function callbackfn(previousValue, currentVaule, currentIndex, array), initialValue)
function callbackfn(previousValue, currentVaule, currentIndex, array)
:必需参数,指定回调函数,最多可以接收4个参数:
previousValue:通过上一次调用回调函数获得的值。如果向 reduce() 方法提供 initialValue,则在首次调用函数时,previousValue 为 initialValue。
currentVaule:当前元素数组的值。
currentIndex:当前数组元素的数字索引。
array:包含该元素的数组对象。
initialValue
:可省略的参数,传递给函数的初始值。
【相关推荐:javascript视频教程、编程视频】
以上就是javascript数组怎么求平均数的详细内容,更多请关注gxlsystem.com其它相关文章!