简体   繁体   English

无限循环不起作用

[英]Infinite loop doesn't work

I have a loop where I load a json object and I want that the data from the json file will showing in my leaflet map in real time. 我有一个循环,可以在其中加载json对象,并且希望json文件中的数据实时显示在我的传单地图中。 When I add values in the json file, jsonData.length show me the updated lenght, but the loop doesn't increment the variable j. 当我在json文件中添加值时,jsonData.length向我显示更新的长度,但循环不会增加变量j。 How is it possible to increment the variable j, after new values was added to the json file? 在将新值添加到json文件之后,如何增加变量j?

function Loop() {
    setTimeout(function() {
        load_js();
        jsonData=loadJSON();  //load JSON Data

        lat = jsonData[j];
        lon = jsonData[j+1];

        var id = Math.floor((Math.random() * 2) + 1);
        jdl = jsonData.length;
        mapUpdater("" + id, lat, lon);


        if (j < jsonData.length) {
            j=j+2;
        }

        Loop();

    }, 1000)
}

You need to change the scope of j. 您需要更改j的范围。 Or you can add j to argument of Loop function. 或者,您可以将j添加到Loop函数的参数中。

function Loop(j) {
  if (j === undefined)
    j = 0;
  setTimeout(function() {

    load_js();
    jsonData = loadJSON(); //load JSON Data

    lat = jsonData[j];
    lon = jsonData[j + 1];

    var id = Math.floor((Math.random() * 2) + 1);
    jdl = jsonData.length;
    mapUpdater("" + id, lat, lon);


    if (j < jsonData.length) {
      j = j + 2;
    }

    Loop(j);

  }, 1000)
}
Loop();

Thanks for your help guys. 感谢您的帮助。 Maybe I didn't elaborated my problem enough. 也许我没有详细说明我的问题。

I found the problem on my own. 我自己发现了问题。 I think the if condition was the problem. 我认为如果条件是问题所在。

I think the array was out of range. 我认为阵列超出范围。 The answer to this problem was this: 这个问题的答案是这样的:

I changed this: 我改变了这个:

if (j < jsonData.length) {
            j=j+2;
        }

to this: 对此:

if (j < jsonData.length-2) {
            j=j+2;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM