[英]How to reverse the order in a FOR loop
I've a simple FOR statement like this:我有一个简单的 FOR 语句,如下所示:
var num = 10,
reverse = false;
for(i=0;i<num;i++){
console.log(i);
}
when reverse is false I want it to return something like [0,1,2,3,4,5,6,7,8,9]当reverse为 false 我希望它返回类似 [0,1,2,3,4,5,6,7,8,9]
but, when reverse is true, it should return [9,8,7,6,5,4,3,2,1,0]但是,当reverse为真时,它应该返回 [9,8,7,6,5,4,3,2,1,0]
Which is the most efficient way to get this result, without checking every time if reverse is true or false inside the loop?哪个是获得此结果的最有效方法,无需每次都检查循环内的reverse是真还是假?
I don't want to do this:我不想这样做:
var num = 10,
reverse = false;
for(i=0;i<num;i++){
if(reverse) console.log(num-i)
else console.log(i)
}
I would like to check reverse only one time outside the loop.我只想在循环外检查一次反向。
var num = 10,
reverse = false;
if(!reverse) for( var i=0;i<num;i++) log(i);
else while(num-- ) log(num);
// to avoid duplication if the code gets long
function log( num ) { console.log( num ); }
EDIT:编辑:
As noted in the comments below, if i
is not declared elsewhere and you do not intend for it to be global, then declare it with the other variables you declared.正如下面的评论中所指出的,如果i
未在其他地方声明并且您不打算将其设为全局,则使用您声明的其他变量对其进行声明。
And if you don't want to modify the value of num
, then assign it to i
first.如果您不想修改num
的值,则先将其分配给i
。
var num = 10,
reverse = false,
i;
if(!reverse) for(var i=0;i<num;i++) log(i); // Count up
else {var i=num; while(i--) log(i);} // Count down
function log( num ) { console.log( num ); }
Try use 2 loops:尝试使用 2 个循环:
if (reverse) {
for(i=num-1;i>=0;i--){
console.log(i)
}
}
else {
for(i=0;i<num;i++){
console.log(i)
}
}
var num = 10,
reverse = false;
for (var i = 0, n = reverse?num-1:0, d = reverse?-1:1; i < num; i++, n+=d) {
console.log(n);
}
This is equivalent to the following, which is more readable, but less compact:这等效于以下内容,它更具可读性,但不那么紧凑:
var num = 10,
reverse = false;
var start = reverse ? num-1 : 0,
end = reverse ? -1 : num,
step = reverse ? -1 : 1;
for (var i = start; i != end; i += step) {
console.log(i);
}
Edit:编辑:
Actually, these two solutions are not identical, because the first one has an additional increment operation.实际上,这两个解决方案并不相同,因为第一个解决方案有一个额外的增量操作。 Still, it is negligible from performance point of view.尽管如此,从性能的角度来看,它可以忽略不计。 If you really want to get a compact solution that has the best performance, you can do the following (not for the faint of heart):如果您真的想获得具有最佳性能的紧凑解决方案,您可以执行以下操作(不适合胆小的人):
var num = 10,
reverse = false;
for (var r=reverse, i=r?num-1:0, n=r?-1:num, d=r?-1:1; i!=n; i+=d) {
console.log(i);
}
This has the advantage of having a single control structure, a single test in each loop, and a single iterator addition.这具有单个控制结构、每个循环中的单个测试和单个迭代器添加的优点。 It is not as fast as having an iterator increment/decrement, but only marginally so.它没有迭代器递增/递减那么快,但只是略微如此。
var start; var end; var inc;
if (reverse) {
start = num-1; end = 0; inc = -1;
}
else {
start = 0; end = num-1; inc = 1;
}
for(i=start;i!=end;i+=inc){
console.log(i)
}
I just came across the need for this the other day.前几天我刚遇到这个需求。 Here's how I did it:这是我如何做到的:
var num = 10,
i = 0,
direction = 1,
reverse = false;
if(reverse)
i = num + (direction = num = -1);
for(; i !== num; i += direction) {
console.log(i);
}
No need for separate loops, and no need to do math to calculate the proper i
in the loop.不需要单独的循环,也不需要做数学运算来计算循环中的正确i
。
So if reverse
is true
...所以如果reverse
是true
......
i
(which represents our first item) becomes num - 1
, so we're now starting on what would have been the last item i
(代表我们的第一个项目)变成num - 1
,所以我们现在从最后一个项目开始
num
(which represents out of bounds) becomes -1
, so we're now stopping on what would have been the first item num
(代表越界)变为-1
,所以我们现在停止在第一个项目上
direction
is -1
, which means it will decrement when we do i += direction
direction
是-1
,这意味着当我们做i += direction
时它会递减
So by swapping our starting point with our ending point and changing the alteration of i
from 1
to -1
, we'll be going up or down based on those modifications.因此,通过将起点与终点交换并将i
的变化从1
更改为-1
,我们将根据这些修改上升或下降。
I think this meets your requirements:我认为这符合您的要求:
var num = 10;
var reverse = false;
var diff = 0;
if (reverse) {
diff = num - 1;
}
for (i = 0; i < num; i++) {
console.log(Math.abs(diff - i));
}
这是我一直以来做反向循环的方式:
for (i = num; --i >= 0; ) ...
And what's your problem with:你有什么问题:
if (reverse)
{
for(i=num-1; i>=0;i--){
console.log(i);
}
}
else
{
for(i=0;i<num;i++){
console.log(i)
}
}
} }
Roy's is similar to mine, but here's what I was thinking.罗伊的和我的很相似,但这是我的想法。 I'll give you what I wrote in C# and how I think it translates to Javascript.我会给你我用 C# 写的东西,以及我认为它是如何转换成 Javascript 的。
C# C#
int num = 10;
bool reverse = true;
for (int i = reverse ? num : 0; (reverse ? 0 : i) < (reverse ? i : num); i += reverse ? -1 : 1)
{
Console.Write((reverse ? i - 1 : i).ToString());
}
Console.ReadKey();
Javascript Javascript
var num = 10,
reverse = true;
for (int i = reverse ? num : 0; (reverse ? 0 : i) < (reverse ? i : num); i += reverse ? -1 : 1)
{
console.log(reverse ? i - 1 : i);
}
And here's another way这是另一种方式
Javascript Javascript
var num = 10,
reverse = false;
for (int i = 0; i < num; i++)
{
console.log((reverse ? abs(-num + (i + 1)) : i));
}
It seems to work:它似乎有效:
var num = 10;
var z = 1;
var k = -10;
if (reverse ){
k = -1;
z = -1;
}
for(int i = 0; i < 10; i++){
console.log(num+i*z+k);
}
Surely in a language like Javascript there must be a way to define a local function and use that in the loop?当然,在像 Javascript 这样的语言中,必须有一种方法来定义本地函数并在循环中使用它吗?
function SubtractFrom(val, subtractor) {
return val - subtractor;
}
function PassThrough(val) {
return val;
}
var num = 10;
var processor = reverse ? SubtractFrom(num-1) : PassThrough;
for (i = 0; i < num; i++) {
console.log(processor(i));
}
Not knowing Javascript though, I don't know what actual form the function definitions would take.虽然不知道 Javascript,但我不知道函数定义会采用什么实际形式。
//reverse a number
let c = [2,3,5,67,4]
let sum = '';
let d = c.toString().split('')
console.log(d)
for(let i = d.length-1; i >= 0; i--) {
sum += d[i]
}
console.log(sum)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.