for循环本身的值++

时间:2015-03-17 09:11:02

标签: javascript for-loop callback

我对javascript中的for循环有一个相当简单的问题。在我运行一个方法之后,我试图增加值(j在我的代码中),该方法声明了一个回调方法,并在该函数中我增加了值。但我的代码断了,我不确定它是否是有效的JavaScript。但无论我在哪里检查这是有效的JavaScript代码:

http://www.w3schools.com/js/js_loop_for.asp

就像那个,声明3

这是我的代码:

for(j=0; j <= 5; )
{

    var keyContent = window.localStorage[window.localStorage.key(j)];
    console.log(keyContent);
    var dataForm = JSON.parse(keyContent);

    uploadDataAndImage(dataForm, function(data) {  
        console.log(data);
        if(data){

            console.log("Data good");
            j++;
        }
        else
        {

            console.log("Data bad");
            break;
        }
    });         
}

编辑:通过这样做来实现:

var formDataArray = [];
for(j=0; j <= 5; j++ )
{

    var keyContent = window.localStorage[window.localStorage.key(j)];
    console.log(keyContent);
    var dataForm = JSON.parse(keyContent);
    formDataArray[j] = JSON.parse(keyContent);                      
    uploadDataAndImage(formDataArray[j], function(data) {  
        console.log(data);
        if(data){

            console.log("Data good");

        }
        else
        {

            console.log("Data bad");
            return;
        }
    });         
}

2 个答案:

答案 0 :(得分:0)

如果您需要在循环中增加,那么您需要的是 while循环

var j = 0;
while (j <= 5) {
    var keyContent = window.localStorage[window.localStorage.key(j)];
  console.log(keyContent);
  var dataForm = JSON.parse(keyContent);

  uploadDataAndImage(dataForm, function(data) {  
    console.log(data);
    if(data){
        console.log("Data good");
      j++;
    } else {
      console.log("Data bad");
      break;
    }
  });         
}

答案 1 :(得分:-1)

代码中的问题不在于循环,而在于break语句。我建议您通过return声明

进行更改
for(j=0; j <= 5; )
{

    var keyContent = window.localStorage[window.localStorage.key(j)];
    console.log(keyContent);
    var dataForm = JSON.parse(keyContent);

    uploadDataAndImage(dataForm, function(data){
    console.log(data);
    if(data){

        console.log("Data good");
        j++;
    }
    else
    {

        console.log("Data bad");
        return;
    }
    });

}