Is it possible to assign repeat loop to a variable?

1

I am implementing a code where if the received variable does not contain a value it should be done for , otherwise not.

Well, if it were for the "simple" case, it was just to implement the if with the conditions and mount the for according to the result, but that would make the code very large. So I would like to know if it's possible to do the following in JavaScript.

<script language="javascript">
w_valor_1;
w_valor_2;

if(w_valor_1 == ""){
   w_for_1 = "for(i = 0; i < w_b; i++){";
   w_ch_1 = "}";
}
else{
   i = w_valor_1;
   w_for_1 = "";
}
if(w_valor_2 == ""){
   w_for_2 = "for(j = 0; j < w_c; j++){";
   w_ch_2 = "}";
}
else{
   j = w_valor_2;
   w_for_2 = "";
}

w_for_1;
w_for_2;
   m_valores[i][j] = b++;
w_ch_2;
w_ch_1;

</script>
    
asked by anonymous 21.11.2014 / 01:13

1 answer

2

My suggestion is to simply adjust the limits of for to run only once if the variable is set, or N times if it is not:

for( var i = (w_valor_1 === "" ?   0 : w_valor_1  ) ; 
         i < (w_valor_1 === "" ? w_b : w_valor_1+1) ; i++)
    for( var j = (w_valor_2 === "" ?   0 : w_valor_2  ) ; 
             j < (w_valor_2 === "" ? w_c : w_valor_2+1) ; j++)
        m_valores[i][j] = b++;

P.S. Do not forget to always use var before variables , otherwise they will see global ...

But just for reference, here's what you'd have to do if you decided to use eval :

eval(w_for_1 + w_for_2 + "m_valores[i][j] = b++;" + w_ch_2 + w_ch_1);

(remembering that w_ch_1 and w_ch_2 also would need to receive "" within else )

    
21.11.2014 / 07:38