JavaScript - 从函数

时间:2016-05-06 11:08:01

标签: javascript arrays function access

我有这个基本的for循环遍历用户的关注者。我想在console.log中从这个函数外面的关注者列表,因为我想将这个数组与另一个其他数组进行比较。我该怎么做?

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

4 个答案:

答案 0 :(得分:1)

我猜你的SC.get方法是异步的,这就是你无法从中返回userfollowings的原因。

但是,您可以将声明放在外面。这将是不够的,因为在SC.get结束之前将评估console.log。通常,处理异步函数涉及promises或回调。 :

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

这样,将使用正确的userFollowings数组

评估console.log

答案 1 :(得分:0)

在函数外部定义数组。由于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);

答案 2 :(得分:0)

在函数外声明var userFollowings = [];

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

答案 3 :(得分:0)

您可以将代码包装到立即调用的函数中并返回所需的数组:

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