admin管理员组文章数量:1431912
How would you iterate over the following series in Javascript/jQuery:
1, -2, 3, -4, 5, -6, 7, -8, ...
Here is how I do this:
n = 1
while (...) {
n = ((n % 2 == 0) ? 1 : -1) * (Math.abs(n) + 1);
}
Is there a simpler method ?
How would you iterate over the following series in Javascript/jQuery:
1, -2, 3, -4, 5, -6, 7, -8, ...
Here is how I do this:
n = 1
while (...) {
n = ((n % 2 == 0) ? 1 : -1) * (Math.abs(n) + 1);
}
Is there a simpler method ?
Share Improve this question asked Jun 5, 2011 at 13:10 Misha MoroshkoMisha Moroshko 172k230 gold badges520 silver badges760 bronze badges 08 Answers
Reset to default 11You could keep two variables:
for (var n = 1, s = 1; ...; ++n, s = -s)
alert(n * s);
This is simpler
x = 1;
while (...) {
use(x);
x = - x - x / Math.abs(x);
}
or
x = 1;
while (...) {
use(x);
x = - (x + (x > 0)*2 - 1);
}
or the much simpler (if you don't need to really "increment" a variable but just to use the value)
for (x=1; x<n; x++)
use((x & 1) ? x : -x);
That looks about right, not much simpler than that. Though you could use n < 0
if you are starting with n = 1
instead of n % 2 == 0
which is a slower operation generally.
Otherwise, you will need two variables.
How about:
var n = 1;
while(...)
n = n < 0 ? -(n - 1) : -(n + 1);
You could always just use the following method:
for (var i = 1; i < 8; i++) {
var isOdd = (i % 2 === 1);
var j = (isOdd - !isOdd) * i;
}
Which is similar, by the way, to how you'd get the sign (a tri-state of -1, 0 or 1) of a number in JavaScript:
var sign = (num > 0) - (num < 0)
for (var n = 1; Math.abs(n) < 10; (n ^= -1) > 0 && (n += 2))
console.log (n);
How about some Bit Manipulation -
n = 1;
while(...)
{
if(n&1)
cout<<n<<",";
else
cout<<~n+1<<",";
}
Nothing beats the bits !!
How about:
while (...)
{
if (n * -1 > 0) { n -= 1; }
else { n += 1; }
n *= -1;
}
seems to be the simplest way.
本文标签: javascriptHow to iterate over the series 12345
版权声明:本文标题:javascript - How to iterate over the series: 1, -2, 3, -4, 5, -6, 7, -8, ...? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743850570a2549931.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论