如果实现了开关盒,我如何从循环中退出(循环内有一个开关)

时间:2019-02-01 14:35:10

标签: javascript

如果实现了切换用例(循环内有一个开关),我如何从循环中退出。

function playInbestPlace() {
  console.log("hello from playInbestPlace ")
  findEmptyarea();
  for (var i = 0; i < indexOfEmpty.length; i++) {
    var elem = indexOfEmpty[i];
    switch (elem) {
      case 0:
        cells[elem].childNodes[0].append("o");
        break;
      case 2:
        cells[elem].childNodes[0].append("o");
        break;
      case 4:
        cells[elem].childNodes[0].append("o");
        break;
      case 6:
        cells[elem].childNodes[0].append("o");
        break;
      case 8:
        cells[elem].childNodes[0].append("o");
        break;
    }
  }
}

我希望它在任何情况下都有效。

2 个答案:

答案 0 :(得分:2)

您可以添加变量found,如果它是true,则可以跳出循环:

function playInbestPlace() {
  console.log("hello from playInbestPlace ")
  findEmptyarea();
  for (var i = 0; i < indexOfEmpty.length; i++) {
    var elem = indexOfEmpty[i];

    var found = false; // initial found is false

    switch (elem) {
      case 0:
        cells[elem].childNodes[0].append("o");
        found = true;
        break;
      case 2:
        cells[elem].childNodes[0].append("o");
        found = true;
        break;
      case 4:
        cells[elem].childNodes[0].append("o");
        found = true;
        break;
      case 6:
        cells[elem].childNodes[0].append("o");
        found = true;
        break;
      case 8:
        cells[elem].childNodes[0].append("o");
        found = true;
        break;
    }

    if(found) // break out if it's true
        break;
  }
}

答案 1 :(得分:0)

可以在验证某些条件后使用标志变量从循环中中断。

function playInbestPlace() {
  console.log("hello from playInbestPlace ");
  findEmptyarea();

  var keepOnLooping = true;

  for (var i = 0; keepOnLooping && i < indexOfEmpty.length; i++) {
    if (elem % 2 === 0) {
      cells[elem].childNodes[0].append("o");

      keepOnLooping = false;
    }
  }
}

我还在答案中添加了epascarello优化。