【问题标题】:Why function inside while loop does not work?为什么while循环内的函数不起作用?
【发布时间】:2021-06-16 20:10:24
【问题描述】:

我想使用while 循环循环和激活函数 5 次。但是我在使函数 myFunctionwhile 循环内工作时遇到问题。如果我删除该函数,该循环将自行工作。怎么了?

var c = 0;
var p = 0;

while (c < 5 && p < 5) {
  function myFunction() { // How to make this function work?
    c++;
    document.write(c);
  }

  if (c == 5) {
    document.write(c);
    document.write('computer win');
  }
  else if (p == 5) {
    document.write('player win');
  }
}

【问题讨论】:

  • 您在循环中声明了一个函数,但没有调用它。

标签: javascript function while-loop


【解决方案1】:
    var c = 0;
    var p = 0;

    function myFunction() {

        c++;
        document.write(c);
    }


while (c < 5 && p < 5) {

    myFunction();

    if (c == 5) {
        document.write(c);
        document.write('computer win');
    } else if (p == 5) {
        document.write('player win');
    }

}

在 JavaScript 或任何其他语言中,您必须定义调用它的函数。在循环中定义函数是一种非常糟糕的做法,可能会出错。

【讨论】:

    【解决方案2】:

    您在循环中声明了一个函数,但没有调用它。

    function myFunction() { // how to make this function work?
      c++;
      document.write (c); 
    } 
    
    var c = 0;
    var p = 0;
    
    while ( c < 5 && p < 5) {
      myFunction();
      if ( c == 5 ) {
        document.write (c); 
        document.write ('computer win');
      } else if ( p == 5 ) {
        document.write ('player win');
      }
    }

    【讨论】:

    【解决方案3】:

    你没有调用这个函数,只是声明了它。

    【讨论】:

      猜你喜欢
      • 2022-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 2021-09-08
      • 2022-01-26
      • 1970-01-01
      相关资源
      最近更新 更多