2016-11-23 4 views
0

配列全体を印刷すると印刷されますが、要素ごとに印刷しようとすると、定義されていません。これは私の関数です。関数の終わりに配列を出力します。クライアント関数はajax API.iに接続するために使用され、ajax関数を介してデータベースから特定の文字列に一致する整数IDを取得し、2つの配列にプッシュします。それも、あなたの通話が終了していない次の行に取り組んでいきます意味Javaスクリプト配列が未定義

function fetch() { 
var arrayForClass = [];//this is a array get undefined at the end 
var arrayForMessage = [];//this is a array get undefined at the end 
exceptionPattern =""; 
receivedData.length = 0; 
var queryInfo; 
var queryForSearchCount = { 
    tableName: "LOGANALYZER", 
    searchParams: { 
     query: "_eventTimeStamp: [" + from + " TO " + to + "]", 
    } 
}; 

client.searchCount(queryForSearchCount, function (d) { 
    if (d["status"] === "success" && d["message"] > 0) { 
     var totalRecordCount = d["message"]; 
     queryInfo = { 
      tableName: "LOGANALYZER", 
      searchParams: { 
       query: "_eventTimeStamp: [" + from + " TO " + to + "]", 
       start: 0, //starting index of the matching record set 
       count: totalRecordCount //page size for pagination 
      } 
     }; 
     client.search(queryInfo, function (d) { 
      var obj = JSON.parse(d["message"]); 
      if (d["status"] === "success") { 
       for (var i = 0; i < obj.length; i++) { 
        if(obj[i].values._level === "ERROR" || obj[i].values._level === "WARN"){ 
         receivedData.push([{ 
          date: new Date(parseInt(obj[i].values._eventTimeStamp)).toUTCString(), 
          level: obj[i].values._level, 
          class: obj[i].values._class, 
          content: obj[i].values._content, 
          trace: (obj[i].values._trace ? obj[i].values._trace : ""), 
          timestamp: parseInt(obj[i].values._eventTimeStamp) 
         }]); 
        }else{ 
         continue; 
        } 
       } 
       console.log(receivedData); 
       for (forLoopI = 0; forLoopI < receivedData.length; forLoopI++){ 
        var className = receivedData[forLoopI][0].class; 
        var strclassname = className.toString(); 
        var messageContent = receivedData[forLoopI][0].content; 
        queryInfo = { 
         tableName: "EXCEPTION_CLASS_FOR_ERROR_PATTERNS", 
         searchParams: { 
          query: "class_name: "+ strclassname + "", 
          start: 0, //starting index of the matching record set 
          count: 1 //page size for pagination 
         } 
        }; 
        client.search(queryInfo,function(d){ 
         var obj = JSON.parse(d["message"]); 
         if (d["status"] === "success") { 
          var num = obj[0].values.id; 
          var strnum = num.toString(); 
          arrayForClass.push(strnum); 
         }else{ 
           $(canvasDiv).html(gadgetUtil.getCustemText("No content to display","error while creating the error pattern" + 
           " please try again")); 
         } 
        },function(error){ 
          console.log(error); 
          error.message = "Internal server error while data indexing."; 
          onError(error); 
        }); 
        queryInfo = { 
          tableName: "ERROR_MESSAGE_CONTENTS", 
          searchParams: { 
           query: "message: \""+ messageContent + "\"", 
           start: 0, //starting index of the matching record set 
           count: 1 //page size for pagination 
          } 
        }; 
        client.search(queryInfo,function(d){ 
          var obj = JSON.parse(d["message"]); 
          console.log(obj); 
          if (d["status"] === "success") { 
            var num2 = obj[0].values.id; 
            var strnum2 = num2.toString(); 
            arrayForMessage.push(strnum2); 
          }else{ 
           $(canvasDiv).html(gadgetUtil.getCustemText("No content to display","error while creating the error pattern" + 
           " please try again")); 
          } 
        },function(error){ 
          console.log(error); 
          error.message = "Internal server error while data indexing."; 
          onError(error); 
        }); 
       } 
      } 
     }, function (error) { 
      console.log(error); 
      error.message = "Internal server error while data indexing."; 
      onError(error); 
     }); 
    }else{ 
     $(canvasDiv).html(gadgetUtil.getCustemText("No content to display","there are no error patterns which include this error" + 
     " please try another one")); 
    } 
}, function (error) { 
    console.log(error); 
    error.message = "Internal server error while data indexing."; 
    onError(error); 
}); 
console.log("------------------"); 
for (var j = 0; j < 8; j++) { 
    console.log(arrayForClass[j]);//prints undefine 
} 
console.log("------------------"); 
console.log(arrayForClass[0]); //prints undefine 
console.log(arrayForClass);//prints corectly 
console.log(arrayForMessage);//printd corectly 

}

this is the out put.

+0

上記のコードのどの部分が機能していませんか? – Joe

+0

あなたは私たちに未定義と配列を含むすべての結果を表示できますか? – Aks

+0

コードの終わり私は未定義の配列をコメントしました。 –

答えて

1

あなたのAPIの呼び出しは非同期です。

あなたのconsole.logがまだ存在しない変数を参照しているため、undefinedが届きます。その時点でarrayForClassが空であるため、arrayForClass [0]は存在しません。既存の変数にconsole.log、でもそれは、現時点では空だが、あなたのデバッガツールは、あなたのデータが入って来た時にコンソールであなたのためにそれを更新することにより、スマートにしようとしているので、

次の行は、正しい結果を得る。

あなたが本当にその時点で実際の値を確認したい場合は、あなたが何らかの形で、たとえば、それは不変にする必要があります。

console.log(JSON.parse(JSON.stringify(arrayForClass))); 

あなたが必要that.Ifのようなコンソールでデータを取得し、なぜこれだけ説明していますこれらの変数を使用するには、それぞれの呼び出しに関するコールバック関数の内部で行う必要があります。

+0

別の関数でこれらの配列を使用したい場合はどうすればいいですか? –

+0

私が言ったように、あなたの関数はコールバック関数の中から呼び出さなければなりません。 async-callbackのアイデアを得るためにこのスレッドを読むことができます:http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call。 – Hereblur

関連する問題