简体   繁体   English

For循环中的嵌套循环

[英]Nesting loops within For loop

I have a long line of code which runs fine, but I was wondering if a nested If loop within the outer For loop would shorten the code, and if so, what would be the appropriate way to write this nested loop. 我有一长串可以正常运行的代码,但我想知道外部For循环中的嵌套If循环是否会缩短代码,如果这样,编写此嵌套循环的合适方法是什么。

This is for a JavaScript array which has nested objects called by counter i. 这是针对JavaScript数组的,该数组具有由计数器i调用的嵌套对象。 Within each object are key:value pairs. 每个对象内都有key:value对。 Myopia, Maple, and truckdriver are the keys, and the returned values are numbers 0 to infinity. 键是近视,枫木和卡车司机,返回值是从0到无穷大的数字。

for (let i = 0; i < z; i++) {
  for (let i = 0; i < 49; i++) {
      y[i].truckdriver = 0;
  }
  for (let i = 49; i < (z - 1); i++) {
      if (y[i].Myopia > 0 && y[i].Maple < y[i].Myopia) {
           y[i].truckdriver = 0;
      } else if ((i + 1) >= z) {
           y[i].truckdriver = 0;
      } else if (y[i].Myopia > 0 && y[i + 1].Maple < y[i].Myopia) {
           y[i].truckdriver = 1;
      } else if ((i + 2) >= z) {
           y[i].truckdriver = 0;
      } else if (y[i].Myopia > 0 && y[i + 2].Maple < y[i].Myopia) {
           y[i].truckdriver = 2;
      } else if ((i + 3) >= z) {
           y[i].truckdriver = 0;
      } else if (y[i].Myopia > 0 && y[i + 3].Maple < y[i].Myopia) {
           y[i].truckdriver = 3;
      } else {
           y[i].truckdriver = 0;
      }
  }
  for (let i = (z - 1); (i < z); i++) {
      y[i].truckdriver = 0;
  }

}

I hope to shorten this code while retaining its functionality. 我希望在保留其功能的同时缩短此代码。

Some minor room for shortening. 有一些小的空间可以缩短。

  • You can dedupe the 1st and 3rd for loops with a single for loop setting all truckdriver values to 0 initially. 您可以使用单个for循环将第一个和第三个for循环进行重复数据删除,最初将所有truckdriver值设置为0
  • This also allows removing the last else case, as truckdriver is already 0 这也允许删除其他情况,因为truckdriver已经是0
  • You can remove the branch (i+1) >= z , as always false since you iterate i while < (z - 1) 您可以删除分支(i+1) >= z ,因为总是在< (z - 1) i进行迭代,所以它总是错误的
  • Extracting the check y[i].Myopia > 0 makes your code longer in # of lines, but shorter in character count and much easier to read 提取支票y[i].Myopia > 0使您的代码在#行中更长,但在字符数方面更短y[i].Myopia > 0易于阅读
  • Lastly, as you yourself mentioned, the if statements and their then clauses are very similar and can be reused inside a for loop. 最后,正如您自己所提到的,if语句及其then子句非常相似,可以在for循环内重用。
for (let i = 0; i < z; i++)
  y[i].truckdriver = 0;

for (let i = 49; i < (z - 1); i++) {
  if (y[i].Myopia > 0)
    continue;

  for (let j = 0; j <= 3; j++)
    if (i + j < z && y[i + j].MAPLE < y[i].Myopia) {
      y[i].truckdriver = j;
      break;
    }
}

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

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