admin管理员组文章数量:1415134
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
4 Answers
Reset to default 3Another, 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)
The first is good and working. for this:
for ( i=0; i<4; dr?(i++):(i--) )
Check jsFiddle here
The Second one is NOT ok as for loop expects an identifier and instead got 'if'.
本文标签: Javascript conditional increment or decrement inside for loop propertiesStack Overflow
版权声明:本文标题:Javascript: conditional increment or decrement inside for loop properties - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745197781a2647223.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论