如何迭代序列:1, -2, 3, -4, 5, -6, 7, -8, ...?
您将如何在 Javascript/jQuery 中迭代以下系列:
1, -2, 3, -4, 5, -6, 7, -8, ...
这是我的做法:
n = 1
while (...) {
n = ((n % 2 == 0) ? 1 : -1) * (Math.abs(n) + 1);
}
有更简单的方法吗?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以保留两个变量:
You could keep two variables:
这更简单
或
更简单(如果您不需要真正“递增”变量而只是使用该值)
This is simpler
or
or the much simpler (if you don't need to really "increment" a variable but just to use the value)
看起来不错,比这简单不了多少。虽然你可以使用
n < 0
如果您从n = 1
而不是n % 2 == 0
开始,这通常是一个较慢的操作。否则,您将需要两个变量。
That looks about right, not much simpler than that. Though you could use
n < 0
if you are starting withn = 1
instead ofn % 2 == 0
which is a slower operation generally.Otherwise, you will need two variables.
怎么样:
How about:
您始终可以使用以下方法:
顺便说一句,这与在 JavaScript 中获取数字的符号(-1、0 或 1 的三态)类似:
You could always just use the following method:
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:
一些位操作怎么样?
没有什么比位更好的了!
How about some Bit Manipulation -
Nothing beats the bits !!
怎么样:
似乎是最简单的方法。
How about:
seems to be the simplest way.