简体   繁体   中英

JavaScript - access array from outside of function

I have this basic for loop that iterates through a user's followers. I want to console.log the list of followers from outside of this function as I want to compare this array to another another array somewhere else. How do I do this?

    // Run through user's followers
    SC.get('/users/9110252/followings',function(followings) {

    var userFollowings = [];


        for(i = 0; i < followings.collection.length; i++) {         

            userFollowings.push(followings.collection[i].username);           

        }   

    });

    console.log(userFollowings);

I guess your SC.get method is asynchronous, and that's why you can't return userfollowings from it.

However, you can put the declaration outside. This won't be enough as the console.log would be evaluated before the end of SC.get. Usually, dealing with asynchronous functions involves promises or callbacks. :

    var userFollowings = [];
        SC.get('/users/9110252/followings').then(function(followings) {
            for(i = 0; i < followings.collection.length; i++) {  
userFollowings.push(followings.collection[i].username); 
            }   

        }).done(function() {
        console.log(userFollowings);
    });

That way, console.log will be evaluated with the right userFollowings array

Define the array outside of the function. It can use it thanks to Closure .

var userFollowings = [];

// Run through user's followers
SC.get('/users/9110252/followings',function(followings) {
    for(i = 0; i < followings.collection.length; i++) {         
       userFollowings.push(followings.collection[i].username);           
    }   
});

console.log(userFollowings);

Declare var userFollowings = []; outside the function.

var userFollowings = [];
// Run through user's followers
SC.get('/users/9110252/followings',function(followings) 


    for(i = 0; i < followings.collection.length; i++) {         

        userFollowings.push(followings.collection[i].username);           

    }   

});

console.log(userFollowings);

You can just wrap your code into immediately invoked function and return the needed array:

var userFollowings = function(){ 
    var len = followings.collection.length, userFls = [];
    SC.get('/users/9110252/followings',function(followings) {          
        while (len--) {
            userFls.push(followings.collection[len].username);
        }
    });

    return userFls;
}();

console.log(userFollowings);

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