0

我在使用以下 javascript 函数时遇到的问题是,它以“不是程序员”的形式返回 mostpopular 的字符串值,因此尽管它在放置我的 console.log 命令的位置执行正确的操作,但它返回了最流行的变量'没有被修改。如果我正在修改顶部的变量,为什么它不会返回修改...它几乎就像 javascript 创建一个实例,它只适用于测试函数的本地设置(如果我放置 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;
4

1 回答 1

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;
于 2013-10-08T16:50:40.563 回答