javascript - Collect variables using a loop -


i have commented on answer found; however, have created account , not have required reputation. answer on link:

calculate average of 5 numbers using 2 functions , onchange event handlers

if scroll down, answer given robg. in script mentions can collect variables in loop instead of manually calling them, not how this. if give me insight on how this, appreciated.

thanks in advance, have spent close 7 hours trying figure out.

here's code other page:

    function calcavg(one, two, three, four, five) {      // note these collected using loop     var 1 = document.totalf.one.value;     var 2 = document.totalf.two.value;     var 3 = document.totalf.three.value;     var 4 = document.totalf.four.value;     var 5 = document.totalf.five.value;      // @ point you'd validate values retrieved     // form , deal junk (remove it, stop processing,      // ask value, etc.)      // pass values performcalc , store result     var average = performcalc([one, two, three, four, five]);      // result     document.totalf.res.value = average;      // there's no need return statement     // function doesn't need return value     // though empty return statement harmless     // return       } 

in script mentions can collect variables in loop instead of manually calling them, he not how this.

it does, in 2 steps.

  1. calcavg() collects variables in array passed performcalc():

    var average = performcalc([one, two, three, four, five]); 

    the [...] in snippet array literal and, in case, creates new array 5 input values elements.

    it's similar using array constructor:

    var average = performcalc(new array(one, two, three, four, five)); 
  2. performcalc() takes array, passed values argument, , loops on them:

    // loop on values, note values strings // need converted numbers before being added (var i=0, ilen=values.length; i<ilen; i++) {    // unary "+" operator cooerce value number   // in real life, value checked before being added   // avoid errors junk input   sum += +values[i]; } 

Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -