“for”循环后JavaScript代码中断

时间:2017-04-10 07:35:19

标签: javascript for-loop

我写了一个简单的地理位置代码,由于某种原因,打破...请参考下面引用的代码部分中的注释,这些注释显示一切都很好,从哪个点断开。

var city = "Unknown";
var area = "Unknown";
var lr = w.results.length;
for (var n = 0; n <= lr; n++)
{
    var la = w.results[n].address_components.length;
    for (var m = 0; m <= la; m++)
    {
        if (w.results[n].address_components[m].types[0] == "locality")
        {
            city = w.results[n].address_components[m].long_name;
            break;
        }
        else if (w.results[n].address_components[m].types[0] == "administrative_area_level_2")
        {
            area = w.results[n].address_components[m].long_name;
            break;
        }
    } //Whatever I put here, still works
} //Now it breaks, and everything below never runs
if (city == "Unknown")
{
    city = area;
}

我在Tasker(Android)中运行它并且没有任何错误可以给出提示。但是,必须是一个愚蠢的错误。提前谢谢!

2 个答案:

答案 0 :(得分:0)

你永远不会离开for循环,这就是为什么它不起作用。

您可以在第二个if(condition) { break; }循环下方for以下使用。 只需找到用作条件的内容。

答案 1 :(得分:0)

您可以使用标签来突破嵌套的for循环。 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

另一种方法是在断开之前将m变量设置为lr + 1,但在继续之前仍然会运行外部循环的其余部分。

var city = "Unknown";
var area = "Unknown";
var lr = w.results.length;
outer:
for (var n = 0; n <= lr; n++)
{
    var la = w.results[n].address_components.length;
inner:
    for (var m = 0; m <= la; m++)
    {
        if (w.results[n].address_components[m].types[0] == "locality")
        {
            city = w.results[n].address_components[m].long_name;
            break outer;
        }
        else if (w.results[n].address_components[m].types[0] == "administrative_area_level_2")
        {
            area = w.results[n].address_components[m].long_name;
            break outer;
        }
    } //Whatever I put here, still works
} //Now it breaks, and everything below never runs
if (city == "Unknown")
{
    city = area;
}