简体   繁体   中英

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. 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). 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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