如何减少 JavaScript for 循环中的工作量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15743805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:56:43  来源:igfitidea点击:

How to decrement work in JavaScript for loop?

javascript

提问by Wiram Rathod

Below JavaScript loop for increment is working, but for decrement not. How to solve this?

下面的 JavaScript 循环递增正在工作,但递减没有。如何解决这个问题?

for(var i=1; i<5; i++) { alert(i); } work fine

for(var i=10; i<5; i--) { alert(i); } not working

回答by Shwet

Better check it with ease... for decrement use

最好轻松检查它...用于递减使用

for (var i = 10; i > 5; i--) { alert(i); }

回答by Matt

Your conditional check on your second for loop is incorrect. You are saying i=10, and continue while i<5, which would be never.

您对第二个 for 循环的条件检查不正确。你说 i=10,并在 i<5 时继续,这永远不会。

Try

尝试

for(var i=10; i>5; i--) { alert(i); } 

回答by Mikke

The first loop starts with i = 1and increments, so that i = [1, 2, 3, 4]while i < 5. The second one starts with i=10, but the body is never executed, because it should only run when i < 5.

第一个循环以i = 1and开始,所以i = [1, 2, 3, 4]while i < 5。第二个以 开头i=10,但主体永远不会执行,因为它应该只在 时运行i < 5

What you want is probably:

你想要的大概是:

for (var i = 10; i > 5; i--) { alert(i); }

回答by chie7tain

The second parameter of the 'for' loop is the exit condition. The code in the for loop is executed as long the condition is true. For example:

“for”循环的第二个参数是退出条件。只要条件为真,for 循环中的代码就会执行。例如:

for(var i = 0; i < 10; i++){
  console.log([i]);
}
在上面的 for 循环中,退出条件检查是否ii小于1010( i < 10i < 10),这是真的,因为在第一个实例中 i = 0,因此循环进入代码块并运行代码,然后递增并继续,直到退出条件为不再正确。


当您说:for (var i = 10; i < 5; i--){alert[i]}for (var i = 10; i < 5; i--){alert[i]}for 循环中的代码永远不会执行时,您就会明白为什么,因为退出条件的i < 5i < 5计算结果为 false(ii等于1010)。为了实现您的目标,您必须forfor将 for 循环的退出条件更改为:

for (var i = 10; i > 5; i--) {
    alert([i]);
}

回答by Safwat Fathi

You can make it more dynamic by setting i to the length of what you are iterating through:

您可以通过将 i 设置为您正在迭代的长度来使其更具动态性:

const string = "abcd";

for (let i = string.length; i > 0; i--) {
   console.log(str[i]);
}

Notice: if you set the condition to i >= 0you will be ignoring the last element in the array or string as it's 0 indexed base.

注意:如果您将条件设置为i >= 0您将忽略数组或字符串中的最后一个元素,因为它的索引基数为 0。