Home > Article > Web Front-end > How to find the average of an array in javascript
Method to find the average of an array in JavaScript: first obtain all parameters; then convert the obtained parameters into an array; then remove the first and last items in the array; finally convert the The remaining data can be summed and averaged.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
How to find the average of an array in javascript?
js Several ways to find the average of an array
Ideas
Get all the parameters
Convert the obtained parameters into an array
Remove the first and last items in the array
Then add the remaining items in the array Sum the data and take the average value
function sumAverage() { let arr = [] // console.log(arguments) // for (let index = 0; index < arguments.length; index++) { // arr.push(arguments[index]); // } arr=Array.from(arguments) // arr=[...arguments] arr.pop()//pop从后面删除 arr.shift()//shift从前面删除 let sumTotal=0 // for (let index = 0; index < arr.length; index++) { // let item = arr[index] // sumTotal += item // } sumTotal = eval(arr.join('+')) return sumTotal/arguments.length } let result = sumAverage(...[1, 6, 7, 8, 9, 9, 44, 1, 55, 1])//...展开数组 console.log(result)
Technical point:
arguments Get the indefinite number of parameters passed by the function
Place the arguments as an array Convert to array Array.from...structure loop
pop deletes the last item, shift deletes the first item
eval turns string concatenation into arithmetic operation
【 Recommended learning: javascript advanced tutorial】
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!