【问题标题】:Why is this labeled javaScript continue not working?为什么这个标记的javascript继续不起作用?
【发布时间】:2011-09-17 15:06:53
【问题描述】:

我正在使用此代码来应对某些圆圈重叠:

iCantThinkOfAGoodLabelName:
x = genX(radius);
y = genY(radius);
for(i in circles) {
  var thisCircle = circles[i];
  if(Math.abs(x-thisCircle["x"])+Math.abs(y-thisCircle["y"])>radius*2) { //No overlap
    continue;
  } else { //Overlap
    continue iCantThinkOfAGoodLabelName; //<- Line 256
  }
  thisCircle = [];
}

但是当到达 continue 语句时,chrome 的开发者控制台给了我这个:client.html:256 Uncaught SyntaxError: Undefined label 'iCantThinkOfAGoodLabelName'

【问题讨论】:

  • 你试过break而不是continue吗?也许continue 只能跳转到循环语句上的标签。

标签: javascript continue labeled-statements


【解决方案1】:

标签应该紧接在循环之前

x = genX(radius);
y = genY(radius);

iCantThinkOfAGoodLabelName:
for(i in circles) {

【讨论】:

  • 在这种情况下,任何我如何生成 X 和 Y 值的建议都会非常有帮助
  • 已编辑 - 您没有理由不能在标签之前生成它们。标签的存在不会以任何方式影响这些行。
  • 这不起作用的任何原因?我已按照说明进行操作,但我遇到了同样的错误。
【解决方案2】:

标签名称和相关循环之间不应有任何声明。

x = genX(radius);
y = genY(radius);
iCantThinkOfAGoodLabelName:
    for(i in circles) {

修复它。

【讨论】:

    【解决方案3】:

    因为iCantThinkOfAGoodLabelName: 需要在循环之前。

    iCantThinkOfAGoodLabelName:
    for (blah; blah; blah)
        ..
    

    我认为你想要的是一个函数..

    function iCantThinkOfAGoodFunctionName() {
        var x = genX(radius),
            y = genY(radius);
    
        for (i in circles) {
            var thisCircle = circles[i];
            if(Math.abs(x-thisCircle["x"])+Math.abs(y-thisCircle["y"])>radius*2) { //No overlap
                continue;
            } else { //Overlap
                iCantThinkOfAGoodFunctionName();
            }
            thisCircle = [];
        }
    }
    

    【讨论】:

      【解决方案4】:

      我最近遇到了这个问题,我通过在 Node.js 的版本 v0.8.x 中使用循环标签中的所有小写字母来解决它。

      使用 labelname:iCantThinkOfAGoodLabelName: 可能会对您有所帮助。

      其他人已经正确地纠正了你在标签的位置。它应该在for 循环之前。

      Mozilla Developer Network on labels 建议避免使用标签,而是更喜欢calling functionsthrowing 错误。如果可能,您可能会重新考虑使用它们的策略。

      根据结果调用函数的示例:

      var i, j;
      
      for (i = 0; i < 3; i++) {
         for (j = 0; j < 3; j++) {   
            if (i == 1 && j == 1) {
               // we want to ignore and continue
            } else {
               // do work with these variables from inside the doWork function
               // (scoped to whatever scope `this` for loop is in)
               doWork.call(this, i, j); 
            }
         }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-22
        • 2016-12-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多