Reputation: 135
So I want to do something like
for ( var i = 0, j = (arr.length - 1); i < j; (++i; --j;) )
i.e. have two operations, ++i
and --j
, as the stuff that happens after the body of the for loop is executed, the equivalent of
for ( var i = 0, j = (arr.length - 1); i < j; )
{
// ...
++i; --j;
}
Is it possible to do it all in the declaration of the for-loop? Is there some fancy bitwise operation on i
and j
that can do ++i; --j
in a single statement?
Upvotes: 0
Views: 78
Reputation: 24812
While the other answers clearly show how to achieve what you wanted, I'd rather suggest you don't use two counters if you can avoid to. Here you could use arr.length - j - 1
instead of i
.
Upvotes: 1
Reputation: 410
Bitwise operators indeed do the trick:
for(var i=0,j=arr.length-1; i < j; i++ & j--){
alert(arr[i]+arr[j]);
}
This works because ++ and -- have return values. Depending on whether you use them as pre- or postincremenent operator the return value is either the value before or after incrementation. (And analogously with decrement operators)
Since JavaScript does not have strong typing, you can use integer values with bit operators. A number != 0 will be interpreted as true, 0 will be interpreted as false. The & operator is used in order for both operands to be evaluated. && would only evaluate the right hand side if the left hand side evaluates to true.
Needless to say that all of this is unneccessary trickery which really should be replaced by cleaner code. In your example just replace j by arr.length-i-1 everywhere and you won't have to deal with two loop variables.
Upvotes: 1
Reputation: 9997
Is comma operator what your are looking for?
for(var i=0, j=10; i<j; i++, j--)
Upvotes: 1