Is it possible to assign loop repetition to a variable?

Asked

Viewed 65 times

1

I am implementing a code where if the received variable does not contain a value, a for, otherwise, no.

Well, if it were for the "simple" case, it would just implement the if with the conditions and assemble the for as the result, but so would be very large the code. I would like to know if it is possible to do the following excerpt 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>
  • 1

    I imagine the solution is to use the val.

  • @Felipeavelar, reading what you passed on the I came up with a question. With it is possible to realize the for? Would he iterate normally? How to ride with him if that were my case? I’m sorry, it’s a lot of questions and.e'

  • Actually, seeing your code better, I couldn’t understand where you initialize w_b and w_c, but what I would do is initialize both with zero and only change their value, if w_valor_1 and w_valor_2 were different from "" respectively.

  • In the case of w_b and w_c they come from PHP, where it contains a value from a previous page and may contain values of 1...n!

  • @Felipeavelar, is it possible to mount with Eval? If so, could you show me an example with the code I showed you? ' Thanks!

  • @mgibsonbr has already shown how, in addition to giving a better solution than using Eval, which is a little slower. (:

Show 1 more comment

1 answer

2


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

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. Don’t forget to always use var before the variables, otherwise they turn global...

But just for reference, here’s what you’d need to do if you decided to use the eval:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.