简体   繁体   English

如何优化一系列特定条件的for循环?

[英]How can I optimize a for-loop over a list of specific conditions?

I've got a for-loop in JavaScript, iterating over the variable i. 我在JavaScript中有一个for循环,遍历变量i。 In each iteration step, a list of if-conditions is checked. 在每个迭代步骤中,检查条件列表。 For each i, only one of these conditions can be true (or none of them) and every condition is true for exactly one i. 对于每个i,这些条件中只有一个可以成立(或都不成立),并且每个条件对于一个i都成立。 A very simple example would be: 一个非常简单的示例是:

for (i = 1; i <= 10; i++)
{
if (i === 3) {some code ...}
if (i === 7) {some other code ...}
 }

So obviously for 4 <= i <= 10 the condition i === 3 will always fail. 因此很明显,对于4 <= i <= 10,条件i === 3将始终失败。 Is there a way to achieve that if a condition is true for some i, this condition will not be checked any more for the other i's? 有没有一种方法可以实现,如果某个i的条件为真,那么其他i的条件将不再被检查? Can this condition be deleted in some way? 可以某种方式删除此条件吗? This would make the loop much faster. 这将使循环更快。

(Of course the example of above does not make much sense and the real use case is much more complicated.) (当然,上面的示例没有多大意义,实际用例要复杂得多。)

Thank you in advance for your help! 预先感谢您的帮助!

Switch is better for what you're trying to achieve Switch更适合您要实现的目标

for (i = 1; i <= 10; i++)
{
 switch(i){
  case 1:
   some code..;
   break; //once this is called, the statement will stop
  case 3:
   some other code..;
   break;
 }
}

You can use else if statements to skip all of the other conditions once one is found. 一旦找到一个条件,就可以使用else if语句跳过所有其他条件。

for (i = 1; i <= 10; i++) {
    if (i === 3) {some code ...}
    else if (i === 7) {some other code ...}
}

In this case, if i is 3, the other conditions will be skipped. 在这种情况下,如果i为3,则其他条件将被跳过。

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

相关问题 如何在此方案中添加for循环? - How can I add a for-loop in this scenario? 如何使用嵌套的for循环最佳地优化函数 - How to best optimize a function with a nested for-loop 如何使Sublime Text的“改进的本机for循环”增量像普通的for循环一样? - How can I make Sublime Text's “Improved Native for-loop” increment like a normal for-loop? 如何使用for循环遍历子项 - How to iterate over children with for-loop 如何在$(document).ready(function(){})中使用for循环? - How can I use a for-loop within a $(document).ready(function(){})? 如何使用变量内的变量进行for循环工作 - how can I make an for-loop work with a variable inside a variable 如何在样式组件中使用for循环? - How can i use for-loop in styled-components? 如何使用两个if条件遍历Handlebars.js中的对象列表? - How can I iterate over a list of objects in Handlebars.js with two if conditions? 如何执行一个 for-loop function,然后在 for-loop function 完成一个按钮后调用另一个 function? - How can I execute one for-loop function, then call another function after the for-loop function is complete with a button? 如何制定我的for循环代码以在特定的html表单元格中插入值? - How do I formulate my for-loop code to insert values in specific html table cells?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM