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.
calcavg()
collects variables inarray
passedperformcalc()
:var average = performcalc([one, two, three, four, five]);
the
[...]
in snippetarray
literal and, in case, createsnew
array
5 input values elements.it's similar using
array
constructor:var average = performcalc(new array(one, two, three, four, five));
performcalc()
takesarray
, passedvalues
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
Post a Comment