简体   繁体   English

为什么javascript无法修改我的变量?

[英]why is javascript not modifying my variable?

The issue I am having with the following javascript function is that it is returning the string value for mostpopular as "not a programmer", so although it is performing the correct operations where my console.log command is placed its return the mostpopular variable that hasn't been modified. 我使用以下javascript函数遇到的问题是,它以“不是程序员”的身份返回最流行的字符串值,因此尽管它在执行我的console.log命令的位置时执行了正确的操作,但返回的最流行的变量hasn没有被修改。 if I am modifying the variable at the top at why wont it return the modifications... Its almost like javascript makes an instance and it only works in the local setting of the test function(if I place the console.log statement it prints out the correct data). 如果我在顶部修改变量,为什么它不返回修改...就像javascript生成一个实例一样,它仅在测试函数的本地设置中起作用(如果我将console.log语句打印出来,正确的数据)。 Why is this ? 为什么是这样 ?

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;

As mentioned above the history search is Asynchronous and hence it requires a callback execution when completed 如上所述,历史记录搜索是异步的,因此完成后需要回调执行

It will Work like below: 它将像下面这样工作:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM