3

我正在尝试建立一个新项目。这将是一个网站的贸易机器人,现在将我收到的项目存储到我的数据库中,我希望每个项目都发送一些信息(名称,asseid,tradeid,...)。以下代码有效。

offers.on('receivedOfferChanged', function (offer, oldState) {
logger.info(offer.partner.getSteam3RenderedID() + " Offer #" + offer.id + " changed: " + TradeOfferManager.getStateName(oldState) + " -> " + TradeOfferManager.getStateName(offer.state));

// Alert us when we accept an offer
if (offer.state == TradeOfferManager.ETradeOfferState.Accepted) {
    offer.getReceivedItems(function (err, items) {
        if (err) {
            logger.error("Couldn't get received items: " + err);
        } else {
            var names = items.map(function(item) {
                return item.name;
            });
            var assetids = items.map(function(item) { 
                return item.assetid; 
            });
            // Log a comma-separated list of items received
            logger.info("Received: " + names + " " + assetids.join(', '));
        }
    });
}
});`

但问题是,有没有办法缩短以下代码:

var names = items.map(function(item) {
            return item.name;
        });
        var assetids = items.map(function(item) { 
            return item.assetid; 
        });

所以它从数组中获取项目名称,资产ID,......并将它们存储在单独的变量中?

4

1 回答 1

3

您可以使用push()方法在单个循环中将值添加到两个数组中。尝试:

var names = [],
    assetids = [];

items.forEach(function(item) {
    assetids.push(item.assetid); 
    names.push(item.name); 
});
于 2015-11-02T13:21:04.627 回答