Two methods to find the average: 1. Use forEach() and length attributes to find the average, the syntax is "function f(v){s =v;}array object.forEach(f);avg=s /Array object.length;"; 2. Use reduce() and length attributes to find it, the syntax is "function f(p,c){s=p c;return s;}Array object.reduce(f);avg=s/ Array object.length;".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Method 1: Use forEach() length attribute
Implementation idea:
Use forEach() to iterate through the array to calculate the sum of elements
Use the length attribute to calculate the length of the array
Divide the sum of the array elements by the array Length
Implementation code:
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);
Description:
The forEach() method is used to call each element of the array and pass the element to the callback function.
array.forEach(funtion callbackfn(value, index, array), thisValue)
funtion callbackfn(value, index, array)
: Required parameters, specify the callback function, can receive up to three parameters:
value : The value of the array element.
index: Numeric index of the array element.
array: Array object containing the element.
thisValue
: an omitted parameter, an object that can be referenced by this in the callback function. If thisArg is omitted, the value of this is undefined.
Method 2: Use the reduce() length attribute
Implementation idea:
Use reduce() to iterate over the array to calculate the sum of elements
Use the length attribute to calculate the length of the array
Divide the sum of the array elements by the array Length
Implementation code:
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);
Description:
reduce() method The specified callback function can be called on all elements in the array. The return value of this callback function is the cumulative result, and this return value is provided as a parameter the next time the callback function is called.
array.reduce(function callbackfn(previousValue, currentVaule, currentIndex, array), initialValue)
function callbackfn(previousValue, currentVaule, currentIndex, array)
: Required parameters, specify the callback function, can receive up to 4 parameters:
previousValue: The value obtained by calling the callback function last time. If initialValue is provided to the reduce() method, the previousValue is initialValue when the function is first called.
currentValue: The value of the current element array.
currentIndex: The numeric index of the current array element.
array: Array object containing the element.
initialValue
: Omissible parameter, initial value passed to the function.
【Related recommendations: javascript video tutorial, programming video】
The above is the detailed content of How to find the average of an array in javascript. For more information, please follow other related articles on the PHP Chinese website!

React'slimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem,2)SEOchallengeswithclient-siderendering,3)potentialperformanceissuesinlargeapplications,4)complexstatemanagementasappsgrow,and5)theneedtokeepupwithitsrapidevolution.Thesefactorsshou

Reactischallengingforbeginnersduetoitssteeplearningcurveandparadigmshifttocomponent-basedarchitecture.1)Startwithofficialdocumentationforasolidfoundation.2)UnderstandJSXandhowtoembedJavaScriptwithinit.3)Learntousefunctionalcomponentswithhooksforstate

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScriptfatigueinReactismanageablewithstrategieslikejust-in-timelearningandcuratedinformationsources.1)Learnwhatyouneedwhenyouneedit,focusingonprojectrelevance.2)FollowkeyblogsliketheofficialReactblogandengagewithcommunitieslikeReactifluxonDiscordt

TotestReactcomponentsusingtheuseStatehook,useJestandReactTestingLibrarytosimulateinteractionsandverifystatechangesintheUI.1)Renderthecomponentandcheckinitialstate.2)Simulateuserinteractionslikeclicksorformsubmissions.3)Verifytheupdatedstatereflectsin

KeysinReactarecrucialforoptimizingperformancebyaidinginefficientlistupdates.1)Usekeystoidentifyandtracklistelements.2)Avoidusingarrayindicesaskeystopreventperformanceissues.3)Choosestableidentifierslikeitem.idtomaintaincomponentstateandimproveperform

Reactkeysareuniqueidentifiersusedwhenrenderingliststoimprovereconciliationefficiency.1)TheyhelpReacttrackchangesinlistitems,2)usingstableanduniqueidentifierslikeitemIDsisrecommended,3)avoidusingarrayindicesaskeystopreventissueswithreordering,and4)ens

UniquekeysarecrucialinReactforoptimizingrenderingandmaintainingcomponentstateintegrity.1)Useanaturaluniqueidentifierfromyourdataifavailable.2)Ifnonaturalidentifierexists,generateauniquekeyusingalibrarylikeuuid.3)Avoidusingarrayindicesaskeys,especiall


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)
