为什么这个标记的javaScript继续不起作用?

时间:2011-06-18 03:22:20

标签: javascript continue labeled-statements

我正在使用此代码来解决某些圈子重叠的问题:

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'

4 个答案:

答案 0 :(得分:10)

标签应该紧接在循环之前

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

iCantThinkOfAGoodLabelName:
for(i in circles) {

答案 1 :(得分:7)

因为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 = [];
    }
}

答案 2 :(得分:3)

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

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

修复它。

答案 3 :(得分:1)

我最近遇到了这个问题,我通过在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); 
      }
   }
}
相关问题