2013-10-08 3 views
0

다음 javascript 함수에 문제가있는 것은 mostpopular의 문자열 값을 "프로그래머가 아닌"것으로 반환하기 때문에 내 console.log 명령이 배치 된 올바른 작업을 수행하지만 mostpopular 변수가 반환됩니다. 수정되지 않은 내가 왜 변수를 수정하지 않을 때 맨 위의 변수를 수정하면 ... 거의 자바 스크립트가 인스턴스를 만들고 테스트 함수의 로컬 설정에서만 작동합니다 (console.log 문을 출력하면 출력됩니다). 올바른 데이터). 왜 이런거야 ? 역사 검색 위에서 언급 한 바와 같이자바 스크립트가 내 변수를 수정하지 않는 이유는 무엇입니까?

var mostPopular = "not a programmer"; 
var totalResults = 0; 


function myfunction() { 
    var listOfLanguages = ["Java", "C", "C++", "PHP", "C#", "Visual Basic", "Python", "Objective-C", "Perl", "Javascript", "Ruby"]; 



    for (var i = 0; i < listOfLanguages.length - 1; i++) { 
     chrome.history.search({ 
      text: listOfLanguages[i], 
      maxResults: 100 
     }, function (search_results) { 

      var countOfResults = search_results.length; 
      var langOfResults = listOfLanguages[i - 1]; 

      test(countOfResults, langOfResults); 

     }); 

    } 

    console.log(mostPopular); 
} 

function test(count, lang) { 


    if (count > totalResults) { 

     totalResults = count; 
     mostPopular = lang; 
    } 

} 

window.onload = myfunction; 
+0

당신은 내가 길이를 <'싶지 않아 - 귀하의 루프에 대한 1 '; 'i <길이 '를 원한다. – naomik

+3

'chrome.history.search'는 async이다. – Prinzhorn

+0

자바 스크립트에서 콜백 함수를 이해해야한다. –

답변

2

는 비동기이며, 그것은 다음과 같이 작동합니다

를 완료 할 때 따라서는 콜백 실행이 필요합니다

var mostPopular = "not a programmer"; 
var totalResults = 0; 


function myfunction() { 
    var listOfLanguages = ["Java", "C", "C++", "PHP", "C#", "Visual Basic", "Python", "Objective-C", "Perl", "Javascript", "Ruby"]; 



    for (var i = 0; i < listOfLanguages.length - 1; i++) { 
     chrome.history.search({ 
      text: listOfLanguages[i], 
      maxResults: 100 
     }, function (search_results) { 

      var countOfResults = search_results.length; 
      var langOfResults = listOfLanguages[i - 1]; 

      test(countOfResults, langOfResults); 
      console.log(mostPopular); 
      // The Code will execute whenever the history search results are returned 
     }); 

    } 
// Any code here will be exceuted irrespective of the history search completed or not 

} 

function test(count, lang) { 


    if (count > totalResults) { 

     totalResults = count; 
     mostPopular = lang; 
    } 

} 

window.onload = myfunction; 
관련 문제