This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
                                
                                    (6个答案)
                                
                        
                2年前关闭。
            
        

这是我的代码:

var items = [];

db.scan({TableName: "players"}, function(err, data) {
  for (var i = 0; i < 10; i++) {
      items.push(data.Items[i]);
  }
});


当我做...

console.log(items);


...表明:

[]


当我做...

setTimeout(function() {
    console.log(items);
}, 1000);


...表明:

(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

有没有办法在没有setTimeout的情况下获得正确的填充数组?

最佳答案

我认为您误解了使用回调的意义。您的其他代码应放在回调的内部,例如

db.scan({ TableName: "players" }, function (err, data) {
    var items = [];

    for (var i = 0; i < 10; i++) {
        items.push(data.Items[i]);
    }

    console.log(items);
});

10-06 00:00