By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,659 Members | 1,945 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,659 IT Pros & Developers. It's quick & easy.

Javascript Question

P: 2
1st piece of code allows me to use an alert to compile a list of grades:

Expand|Select|Wrap|Line Numbers
  1. <body onload="loadGrades()">
  2. <button onclick="myFunction()">Add a grade!</button>
  3. <p id="grades"></p>
  4.  
  5.  
  6. <script>
  7. var grades = [10,12,13];
  8.  
  9. function loadGrades(){
  10. document.getElementById("grades").innerHTML =grades;
  11.  
  12. }
  13. function myFunction() {
  14. var grade = prompt("what is the next grade?");
  15. grades[grades.length]=grade;
  16.  
  17. document.getElementById("grades").innerHTML = grades;
  18. }
  19.  
  20. </script>
  21. </body>
  22.  
  23.  
2nd piece of code allows me to calculate the mean of a list of numbers but only when I manipulate the list from within the code:


Expand|Select|Wrap|Line Numbers
  1.  
  2. <script>
  3.  
  4.  
  5. var Grades = [10,20];
  6.  
  7. var sum=0;
  8. if(Grades.length>0){
  9. for(index=0;index<Grades.length;index++){
  10.  
  11. sum+=Grades[index];
  12. }
  13.  
  14.  
  15. document.write(sum/Grades.length);
  16.  
  17. document.write(" is the average of the following grades" + Grades);
  18. }
  19. else
  20. document.write("Emptyy");
  21.  
  22.  
  23. </script>
  24.  
I cannot figure out how to make the new list (when I enter a new number in the prompt) to automatically update the mean of the grades. I would have thought it would have been as easy as cutting and pasting the two parts together but I couldn't get it to work.

Any thoughts wouild be appreciated!

Thanks.
2 Days Ago #1
Share this Question
Share on Google+
1 Reply


gits
Expert Mod 5K+
P: 5,327
well first the array that contains the numbers for your calculation in the 2 script-snippets have different names - thus they are independent from each other when you just want to merge the snippets. But it wouldn't work either then - because you would need to recalculate when the input was made and the array was updated. So wrap the calculation and output of the result into another function as well and call it at the right place.
6 Hours Ago #2

Post your reply

Sign in to post your reply or Sign up for a free account.