【问题标题】:Point out errors in a JavaScript Loop指出 JavaScript 循环中的错误
【发布时间】:2018-04-27 19:22:24
【问题描述】:

这个函数有什么问题?我想给 c_count 加 1 直到达到 100

<script type="text/javascript"> var result = cMat(0); function cMat (c_count) { var limit = 100; match = 1; while (c_count != limit) c_count ++ match; if (c_count == 95) { c_count = 10; } } return (c_count) } </script>

【问题讨论】:

  • 那段代码有什么问题?
  • 看起来您正试图从 cMat 函数外部返回 c_count,而不是返回 resuilt
  • c_count ++ match - 使用 c_count++;++c_count;c_count += match 或 ... 代替。在你的函数定义之后调用result = cMat(0);。在while 之后添加{ 或在末尾删除}

标签: javascript function loops


【解决方案1】:

我想将 c_count 加 1 直到达到 100

c_count 每次达到 95 的值时都会将其重置为 10,因此它永远不会达到您的极限。您的匹配变量似乎没有被使用,因此可以将其删除。要检查的一件事是 c_count 的值相对于 100 的位置。如果它大于 100,则需要减小该值而不是增加它。

 var result = cMat(0); 

 function cMat (c_count) { 
   var limit = 100;
   while (c_count != limit) 
      if(c_count < limit) {
         c_count++;
      } else { // Implied that it's greater than the limit at this point
         c_count--;
      }
   } 
   return c_count;
 } 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2020-09-03
    相关资源
    最近更新 更多