list reduce
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> let arr = [12,44,22,54,52]; let res=arr.reduce(function (tmp,item,index){ alert(`第${index}次,${tmp}+${item}`); return tmp+item; }); </script> </head> <body> </body> </html>
<script> let arr = [12,44,22,54,52]; let res=arr.reduce(function (tmp,item,index){ if (index < arr.length-1){ return tmp+item; }else{ return (tmp+item)/arr.length; } }); alert(res); </script>