最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: conditional increment or decrement inside for loop properties - Stack Overflow

programmeradmin1浏览0评论

I know I can do an IF ELSE, but I need to know if it is possible to set conditional loop, like so:

for ( i=0; i<la; dr?(i++):(i--) ) {}

or

for ( if (dr) { i=0; i<length; i++ } else { i=length-1; i--} ) {}

I know I can do an IF ELSE, but I need to know if it is possible to set conditional loop, like so:

for ( i=0; i<la; dr?(i++):(i--) ) {}

or

for ( if (dr) { i=0; i<length; i++ } else { i=length-1; i--} ) {}
Share Improve this question asked Apr 8, 2015 at 5:25 thednpthednp 4,4794 gold badges35 silver badges51 bronze badges 1
  • No. Just split them up. – Evan Knowles Commented Apr 8, 2015 at 5:27
Add a ment  | 

4 Answers 4

Reset to default 3

Another, still pact (moreso, even) but more readable and efficient way to do it would be:

var str = 'hello';
for(var i=(dr?0:str.length-1), d=(dr?1:-1); str[i]; i+=d) do_something();

And if you put 1 or -1 in dr, which makes sense I think:

for(var i=+(dr===-1&&str.length-1); str[i]; i+=dr) do_something();

Yes it is fine to use a conditional loop but it is not remended as it bees really hard for someone new who tries to understand your code. The code is not readable if you use the first syntax. The second syntax is much readable so I think you should prefer to use it.

But if you are are fine to use the first version of the syntax then go with it. You should always use the code which is easiest to read and maintain.

First is ok. (but you probably have to use a?b:c on your end_condition too) Second is: syntax error ^^

Crazy way:

var str = 'hello';
for(i=(dr?0:str.length-1);(dr?i<str.length:i>=0);(dr?i++:i--)) do_something();

Right way:

   var str = 'hello';
   if(dr)
      for(i=0;i<str.length;i++) do_something();
   else
      for(i=str.length-1;i>=0;i--) do_something();

(code not tested)

  1. The first is good and working. for this:

    for ( i=0; i<4; dr?(i++):(i--) )

    Check jsFiddle here

  2. The Second one is NOT ok as for loop expects an identifier and instead got 'if'.

发布评论

评论列表(0)

  1. 暂无评论