freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../debugging/prevent-infinite-loops-with...

2.3 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7b86367417b2b2512b3d Prevent Infinite Loops with a Valid Terminal Condition 1 使用有效的终端条件防止无限循环

Description

最后一个话题是可怕的无限循环。当您需要程序运行代码块一定次数或满足条件时,循环是很好的工具,但是它们需要终止条件来结束循环。无限循环可能会冻结或崩溃浏览器,并导致一般程序执行混乱,没有人想要。在本节的介绍中有一个无限循环的例子 - 它没有终止条件来摆脱loopy()内的while循环。不要叫这个功能!
function loopy{
whiletrue{
console.log“Helloworld;
}
}
程序员的工作是确保最终达到终止条件,该条件告诉程序何时突破循环代码。一个错误是从终端条件向错误方向递增或递减计数器变量。另一个是在循环代码中意外重置计数器或索引变量,而不是递增或递减它。

Instructions

myFunc()函数包含一个无限循环,因为终端条件i != 4将永远不会计算为false (并且会中断循环) - i将每次递增2然后跳过4因为i是奇数启动。固定在终端条件比较运算符因此该循环仅运行i小于或等于4。

Tests

tests:
  - text: 您的代码应该更改<code>for</code>循环的终端条件(中间部分)中的比较运算符。
    testString: 'assert(code.match(/i\s*?<=\s*?4;/g).length == 1, "Your code should change the comparison operator in the terminal condition (the middle part) of the <code>for</code> loop.");'
  - text: 您的代码应该在循环的终端条件中修复比较运算符。
    testString: 'assert(!code.match(/i\s*?!=\s*?4;/g), "Your code should fix the comparison operator in the terminal condition of the loop.");'

Challenge Seed

function myFunc() {
  for (let i = 1; i != 4; i += 2) {
    console.log("Still going!");
  }
}

Solution

// solution required