當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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);

輸出:

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

相關用法


注:本文由純淨天空篩選整理自AshokJaiswal大神的英文原創作品 Collect.js average() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。