从列表Node.JS中删除项目

时间:2014-06-16 22:29:58

标签: javascript node.js

如果item小于1,是否有人知道如何从以下代码中list删除item.profit

Splice似乎不起作用。

让我们说这会返回如下内容:

item 1, profit = 10
item 2, profit = 5
item 3, profit = -3
item 4, profit = 5
item 5, profit = -2

我正试图以列表结束:

item 1, profit = 10
item 2, profit = 5
item 3, profit = 5

var i = 0;
async.forEach(list, function (item, callback) {

    var url = 'http://www.website.com';
    request(url, function (err, response, html) {
        if (err) {
            console.log(err)
        } else {
            /// some code before....

            item.profit = (some calculation here);

            if (item.profit < 1) {
                console.log("Profit less than 1, so removing from list...");
                list.splice(i, 1); // This doesn't seem to work
            }

            // some code after...

        }
        callback();
    });
}, function (err) { //This is the final callback
    callback(err, list);
});

谢谢,

安东尼

1 个答案:

答案 0 :(得分:3)

请注意,async.forEach()并行处理项目。因此,修改原始列表的条目是一个问题。您可能希望将所有想要的条目保存在新列表中。这是代码:

var i = 0, 
    newList = [];
async.eachSeries(list, function (item, callback) {  // <<<<< done is series to keep
                                                    // the same order as the original
                                                    // list, if you don't care about
                                                    // the order, then use
                                                    // async.each()

  var url = 'http://www.website.com';
  request(url, function (err, response, html) {
    if (err) {
        console.log(err)
    } else {
        /// some code before....

        item.profit = (some calculation here);

        if (item.profit > 0) {
            newList.push(item);
        }

        // some code after...

    }
    callback();
  });
}, function (err) { //This is the final callback
  callback(err, newList);
});