简体   繁体   English

是否可以在 javascript 的一个循环中将结果数减少 7、3、2?

[英]Is it possible to decrement result number by 7, 3, 2 in one loop in javascript?

I'm new to javascript and my weakness has always been for-loops.我是 javascript 的新手,我的弱点一直是 for 循环。 However, right now I'm 95% sure, that I need to use for-loops to achieve my goal.但是,现在我有 95% 的把握,我需要使用 for 循环来实现我的目标。

For an instance: I'm trying to decrement number 45 at first by 7, till it reaches 38:例如:我首先尝试将数字 45 减少 7,直到达到 38:

for (var j = 45; j >= 38; j -=7){
console.log (j);
}

Then I would like to decrement 38 by 3, till it reaches 32:然后我想将 38 减 3,直到达到 32:

for (var l = 38; l >= 32; l -=3){
console.log (l);
}

And then again decrement result by 2 till it reaches 0:然后再次将结果减 2 直到达到 0:

for (var s = 32; s >= 0; s -=2){
console.log (s);
}

And here's the issue that I'm facing: how can I assign these 3 for-loops to one variable, so that when I'm calling for variable, it displays:这是我面临的问题:如何将这 3 个 for 循环分配给一个变量,这样当我调用变量时,它会显示:

45
38
35
32
30
28
.
.
0

Or is there a better alternative?还是有更好的选择?

Thanks!谢谢!

Is it possible to decrement result number by 7, 3, 2 in one loop in javascript?是否可以在 javascript 的一个循环中将结果数减少 7、3、2?

Yes, it is possible.对的,这是可能的。

You could take an object with the values for changing the step variable for the wanted interval.您可以使用 object 的值来更改所需间隔的步长变量。

 var steps = { 45: 7, 38: 3, 32: 2 }, step, j; for (j = 45; j >= 0; j -= (step = steps[j] || step)) { console.log(j); }
 .as-console-wrapper { max-height: 100%;important: top; 0; }

You can do it a single for loop like the following way:您可以像以下方式一样执行单个 for 循环:

 for (var j = 45; j >= 0; ){ console.log (j); if (j>38) j -= 7; else if (j>32) j -= 3; else j -= 2; }

You can just modify your iteration interval depending on what range your current iterator is in.您可以根据当前迭代器的范围修改迭代间隔。

var x = 7;
for( var i = 45; i > 0; i -= x )
{
    if( i <= 38 && i > 32 ) x = 3;
    else if( i <= 32 ) x = 2;
    console.log( i );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM