简体   繁体   中英

Variable scoping in Jquery/Javascript

I have the following code:

var ids = new Array(5);
$(function(){
html5sql.process(sql, 
    function(transaction, results, rowsArray){
        for(var i = 0; i < rowsArray.length; i++){
            ids[i] = rowsArray[i].ID;
                            console.log(ids[i]); //returns the actual value for i
        }
    },
    function(error, statement){
              console.log("Error: " + error.message);       
            }
);
console.log(ids[0]); //returns undefined
});

As you can see, the print out inside the for loop prints the correct value. On the other hand, when I print outside the function I get undefined. What is the problem with the scoping? How can I get the actual value of the array outside the function?

Thanks

var ids = [];

$( function () {

    html5sql.process( sql, function () {

        // LINE A: you are populating your array here

    });

    // LINE B: the array is still empty here

});

LINE A does appear above LINE B in the source code, but that doesn't necessarily mean that it executes sooner. That is because LINE A is inside a function expression which is passed into the process function. This process function will invoke that function expression at some time in the future.

So, basically, LINE B is executed immediately, and LINE A is executed at some point in the future. The function expression is probably bound (as a handler) to a SQL-related event.

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