collect.js average() 方法
average() 方法用于返回集合中所有项目的平均值。此方法是 avg() 方法的别名。
句法:
collect(array).average()
参数: collect() 方法接受一个参数,该参数转换为集合,然后对其应用 average()函数,如果将其应用于对象集合,则可以获取元素。
返回值:此方法返回一个数字,该数字是集合的平均值。
下面的例子说明了 collect.js 中的 average() 方法:
示例 1:
Javascript
const collect = require('collect.js');
let arr = [10, 20, 30];
let average = collect(arr).average();
console.log("Average of the given array: ", average);
Javascript
const collect = require('collect.js');
let arr = [
{
name: 'Rahul',
score: 98,
},
{
name: 'Aditya',
score: 96,
},
{
name: 'Abhishek',
score: 80
},
];
// Converting object to collection
const collection = collect(arr);
// Finding the average of all the score
let averageScore = collection.average('score');
console.log("Average score of students: ", averageScore);
输出:
Average of the given array: 20
示例 2:
Javascript
const collect = require('collect.js');
let arr = [
{
name: 'Rahul',
score: 98,
},
{
name: 'Aditya',
score: 96,
},
{
name: 'Abhishek',
score: 80
},
];
// Converting object to collection
const collection = collect(arr);
// Finding the average of all the score
let averageScore = collection.average('score');
console.log("Average score of students: ", averageScore);
输出:
Average score of students: 91.33333333333333