search
HomeWeb Front-endFront-end Q&AHow to find the average of an array in javascript

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;".

How to find the average of an array in javascript

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

How to find the average of an array in javascript

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

How to find the average of an array in javascript

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the limitations of React?What are the limitations of React?May 02, 2025 am 12:26 AM

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

React's Learning Curve: Challenges for New DevelopersReact's Learning Curve: Challenges for New DevelopersMay 02, 2025 am 12:24 AM

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

Generating Stable and Unique Keys for Dynamic Lists in ReactGenerating Stable and Unique Keys for Dynamic Lists in ReactMay 02, 2025 am 12:22 AM

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

JavaScript Fatigue: Staying Current with React and Its ToolsJavaScript Fatigue: Staying Current with React and Its ToolsMay 02, 2025 am 12:19 AM

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

Testing Components That Use the useState() HookTesting Components That Use the useState() HookMay 02, 2025 am 12:13 AM

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

Keys in React: A Deep Dive into Performance Optimization TechniquesKeys in React: A Deep Dive into Performance Optimization TechniquesMay 01, 2025 am 12:25 AM

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

What are keys in React?What are keys in React?May 01, 2025 am 12:25 AM

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

The Importance of Unique Keys in React: Avoiding Common PitfallsThe Importance of Unique Keys in React: Avoiding Common PitfallsMay 01, 2025 am 12:19 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

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

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)