在带有break的while循环中,这是怎么回事?

时间:2019-06-01 21:54:55

标签: javascript loops break

我试图了解如何使用break语句执行do / while循环。我以为只要执行break语句(前两次迭代,因为那时候if条件为true,但第三次都不是),for循环就会逸出,因此n不会递增。但是行console.log(`n is ${n}`)记录了n is 2 n is 2 n is 5-它如何从2跳到5?我以为第三次是3(如果if条件不成立,因为quot60,而60 % 2等于0,因此break语句未执行)。

  // newArray = [5, 4, 3, 2, 1];

  var quot = 0;
  var loop = 1;
  var n;

  do {
        quot = newArr[0] * loop * newArr[1];
        for (n = 2; n < newArr.length; n++) {
          if (quot % newArr[n] !== 0) {
            break;
          }
        }

        console.log(`n is ${n}`)

        loop++;
   } while (n !== newArr.length);

这是完整的代码(freeCodeCamp challenge的解决方案):

function smallestCommons(arr) {
  // Sort array from greater to lowest
  // This line of code was from Adam Doyle (http://github.com/Adoyle2014)
  arr.sort(function(a, b) {
    return b - a;
  });

  // Create new array and add all values from greater to smaller from the
  // original array.
  var newArr = [];
  for (var i = arr[0]; i >= arr[1]; i--) {
    newArr.push(i);
  }

  // Variables needed declared outside the loops.
  var quot = 0;
  var loop = 1;
  var n;

  // Run code while n is not the same as the array length.
  do {
    quot = newArr[0] * loop * newArr[1];
    for (n = 2; n < newArr.length; n++) {
      if (quot % newArr[n] !== 0) {
        break;
      }
    }

    console.log(`n is ${n}`)

    loop++;
  } while (n !== newArr.length);

  return quot;
}

// test here
smallestCommons([1,5]);

1 个答案:

答案 0 :(得分:0)

您的数组长度为5,因此,如果未执行if语句和break,则n始终为5。

(n = 2; n

上一次执行此操作,n=4, n < newArr.length (which is 5), n++ (now n is 5)

就像您在问题中说的那样:“ if条件不成立,因为quot为60,而60%2等于0,因此不会执行break语句”

您的break语句只会使您早日退出for循环,如果您的for循环完成了整个周期,则n始终为5。

希望如此!