2017-12-12 10 views
0

자바 스크립트 함수에 의해 반환 된 배열 액세스 :나는 다음과 같은 코드를 가지고

$(document).ready(function() { 
    var blu = getData(); 
    console.log(blu); //this shows full the array in the console 
    console.log(blu.length); //this gives back 0 

}); 

다음과 같은 기능으로를 GetData의()

function getData() { 
    var arr = []; 
    var json; 

    $.ajax({ 
     url: "someurl.com", 
     dataType: 'json', 
     data: json, 
     success: function(json) { 
      var x = json.somejson.somenumericvalue //gets the amount of dataentries 
      for (i = 0; i <= x - 1; i++) { 
       arr.push(json.feeds[i].field1); // fill up array with the values from the json feed 
      } 
     } //end of success function 
    }); //end of ajax 
    console.log(arr.length) //shows the correct length of the array 
    return arr; 
} //end of function getData 

문제는 내가 값에 액세스 할 및 (.length와 같은) 메소드를 함수에 채워진 배열로 처리하지만 어떻게 든 작동하지 않습니다. 누구든지 도와 줄 수 있습니까? 건배.

+0

'$ .ajax'는 ** 비동기 ** – charlietfl

답변

0

$ .each 또는 in 루프 용으로 사용할 수 있습니다.

예.

$.each(Blu, function (i, v){//do whatever with array values, i: index, v: value} 

또는

For(i in Blu){//i: index, access your value by Blu[I] & do whatever with your value} 

은 아마 당신은 그것을 통해 반복 할 필요가 당신의 JSON이 어떻게 생겼는지 분명하지 않다

0

을 당신을 도울 것입니다 바랍니다. 당신이 json.feeds를 반복하려는 가정 : CONSOLE.LOG 및 반환이 어디

function getData(){ 
    var arr = []; 
    var json; 
    $.ajax({ 
     url: "someurl.com", 
     dataType: 'json', 
     data: json, 
     success: function(json){ 
      for(var i in json.feeds) { 
       arr.push(json.feeds[i].field1); // fill up array with the values from the json feed 
      } 
      console.log(arr.length)//shows the correct length of the array 
      return arr; 
     } //end of success function 
    }); //end of ajax 
}//end of function getData 

또한 유의하십시오. 나는 자바 스크립트, 특히 클로저와 변수 범위에 대한 기본적인 책을 읽는 것이 좋습니다. 그래서 코드가 작동하지 않고 문제는 ajax, json 또는 객체 반복에 없습니다.

+0

아니요. OP는'dataType : 'json''을 설정하고 있습니다. callbcks에 전달하면 이미 구문 분석됩니다. – charlietfl

+0

예, 감사합니다. 이미 dataType 매개 변수가 나타났습니다. –

0

ajax 호출로 반환 된 json 데이터는 명명 된 배열 인 경우 객체 표기법을 통해 액세스해야합니다. 이러한 데이터 객체의 길이를 검색하려면 다음을 사용하십시오.

Object.keys(data.datanode).length