简体   繁体   English

Array.push无法在Node.js中使用对象

[英]Array.push is not working with objects in Nodejs

How can I add an object as an entry to an array, like I'm trying to do here... 我如何将对象作为数组的条目添加,就像我在这里尝试做的那样...

 displayAccounts(function(data){
    var index;
    var accs = new Array();
    for (index = 0; index < data.length; ++index) {
      rclient.get(data.account, function (info) {
        accs.push({
            account: data.account,
            info: info
          });
      });
    }
    console.log(accs);
  });

Output: 输出:

accs = []

Desired solution: 所需解决方案:

accs = [{account: 'jak', info: 0},{account: 'jil', info: 1}]

The problem is almost certainly that rclient.get is asynchronous , so examining the array after your loop is examining it too soon (the gets have been started , but they haven't finished yet); 问题几乎可以肯定是rclient.get异步的 ,因此在循环之后检查数组会检查它为时过早(获取已开始 ,但尚未完成)。 it will get filled in by callbacks that occur asynchronously. 它会被异步发生的回调填充。 Wait until the last callback has occurred, eg: 等待直到发生最后的回调,例如:

displayAccounts(function(data){
    var index;
    var accs = []; // [] is a better way to write new Array()
    for (index = 0; index < data.length; ++index) 
        rclient.get(data.account, function (info) {
            accs.push({
                account: data.account,
                info: info
            });
            if (accs.length === data.length) {
                // We're done, *now* look at / use the array
                console.log(accs);
            }
        });
    }
});

Note that depending on how rclient.get works, the callbacks may or may not occur in the same order as the requests. 请注意,根据rclient.get工作方式,回调可能会或可能不会以与请求相同的顺序发生。


Side note: That rclient.get(data.account, ... looks suspicious, you're repeatedly requesting the same information. Perhaps rclient.get(data[index].account, ... ? 旁注: rclient.get(data.account, ...看起来可疑,您反复请求相同的信息。也许rclient.get(data[index].account, ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM