兩種求平均數的方法: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 文檔、設計、調試、自動化測試一體化協(xié)作工具:點擊使用
本教程操作環(huán)境:windows7系統(tǒng)、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
:可省略的參數,傳遞給函數的初始值。
【