2013-10-08 107 views
0

我在使用下面的javascript函數時遇到的問題是,它將大多數流行的字符串值作爲「不是程序員」返回,因此儘管它正在執行正確的操作,而我的console.log命令被放置,它將返回最流行的變量沒有被修改。如果我正在修改頂部的變量,爲什麼不返回修改......它幾乎就像JavaScript創建一個實例,它只能在測試函數的本地設置中工作(如果我將它放在console.log語句中,它會打印出來正確的數據)。爲什麼是這樣 ?爲什麼JavaScript不能修改我的變量?

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

你不想'I <長度 - 1'爲您的循環;你只想'我<長度' – naomik

+3

'chrome.history.search'是異步的 – Prinzhorn

+0

你需要了解Javascript的回調函數 –

回答

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; 
相關問題