Page 1 of 1

increment a variable name

Posted: Tue Oct 20, 2009 10:37 am
by desperado
Anyone know how I can increment a variable name within a loop?

I have:

Code: Select all

 
    var j=1;
        for (j=1;j<=4;j++){
            if (document.form1.elements['bh_hole_diam'+j].value > 0){
                var Hole+j = Math.pow((document.form1.elements['bh_hole_diam'+j].value + 0.6),2);
            }else{
                var Hole+j = 0;
            }
            if ((document.form1.elements['bh_notch_w'+j].value > 0) && (document.form1.elements['bh_notch_h'+j].value > 0)){
                var Notch+j = ((document.form1.elements['bh_notch_w'+j].value + 0.3) * (document.form1.elements['bh_notch_h'+j].value + 0.6));
            }else{
                var Notch+j = 0;
            }
        }
   
I'm trying to get results as:

Hole1=
Hole2=
Hole3=
...

Re: increment a variable name

Posted: Tue Oct 20, 2009 11:36 am
by kaszu
Better use array

Code: Select all

var Hole = [];
for (j=1;j<=4;j++){
    if (...) {
        Hole[j] = ...;
    } else {
        Hole[j] = 0;
    }
    ...
}
 

Re: increment a variable name

Posted: Tue Oct 20, 2009 3:55 pm
by AbraCadaver
I agree on using arrays, but to answer the question (not tested):

1. eval('hole' + j + ' = 0');

or

2. this["hole" + j] = 0;