Javascript将元素插入循环内,不会影响循环外的数组

标签 javascript arrays node.js loops mongoskin

我有一个空数组,我想将项目插入循环内。一旦跳出循环,数组就会丢失所有信息

var result = [];
        users.find({}, {username: true, isOnline: true, uniq: true, _id: false}, function(err, cursor) {
            cursor.each(function(err, item) {
                result.push(item);
                console.log(result); //every iteration the array shows fine
            });

            console.log(result); //array is empty
        });

        console.log(result); //array is empty

最佳答案

您似乎正在使用 Mongoskin ,您可以使用toArray方法将光标转换为Array,这似乎就是您想要的。 看看这个:

http://www.hacksparrow.com/mongoskin-tutorial-with-examples.html

db.collection('stuff').find().toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
});

所以你的代码将如下所示:

var result = [];
        users.find({}, {username: true, isOnline: true, uniq: true, _id: false})
        .toArray(function(err, cursor) {
            // cursor is now an array. forEach is sync.
            cursor.forEach(function(item) {
                result.push(item);
                console.log(result); //every iteration the array shows fine
            });

            console.log(result); // Should not be empty now
            // Add more code in here, if you want to do something with
            // the result array
        });
        // Still empty, because find is async.
        // Your code should go inside of the users.find call
        // and not here
        console.log(result);

这是您将经常使用 Node 处理的事情。对于异步代码,其余代码必须位于异步调用内部。例如,您可以继续处理回调,或使用 Promise。

关于Javascript将元素插入循环内,不会影响循环外的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29976616/

相关文章:

javascript - (ajax和express js) express js授权中间件

javascript - 使用 can.Map.Validate 验证动态对象

javascript - 在将图像分配给 img 标签之前使用 javascript 调整图像大小

c# - 列表的链表或数组实现的优缺点

arrays - 如何将数组存储到 session 中并在 Laravel 中调用它?

node.js - JXCore打包,NPM错误

node.js - nodejs Kue 的条件尝试

javascript - chart.js 颜色不渲染

javascript - 为什么这个使用 Alpine.js 的循环会重复多次?

javascript - 如何在foreach迭代中去掉这个{},需要去掉object