虽然循环没有将正确的结果推送到数组

时间:2016-04-04 13:09:07

标签: javascript arrays sorting

我有一个while循环,它应该迭代一个数组和selectedDate值,以确定一个事件是否会在周末到来,但是它没有正确地过滤掉结果而且我不确定为什么,一切看起来都对我不对。 while loop是否适合此排序作业?

功能

  function(err,results) {
    var i = results.length;
    var theWeekend = [];
    //console.log(results)

    // EVERYTHING WORKS UNTIL HERE
    while(i--) {
      if (0 >= [friday, saturday, sunday].indexOf(results[i].selectedDate)) {
          theWeekend.push(results[i]);
          //console.log(theWeekend);
        }
    }
    callback(err, theWeekend)
    console.log(theWeekend);
    }

[friday, saturday, sunday]为控制台提供了正确的日期:

[ Fri Apr 08 2016 14:00:54 GMT+0100 (BST),
  Sat Apr 09 2016 14:00:54 GMT+0100 (BST),
  Sun Apr 10 2016 14:00:54 GMT+0100 (BST) ]

预期结果应为:

[ { _id: 570260718ef368db32c570c8,
    url: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators',
    title: 'Expressions and operators - JavaScript | MDN',
    selectedDate: Sun Apr 10 2016 01:00:00 GMT+0100 (BST),
    __v: 0 } ]

但是我收到上周末的数据,应该省略:

[ { _id: 56fffb5ceb76276c8f39e3f3,
    url: 'http://londonist.com/2015/11/where-to-eat-and-drink-in-balham',
    title: 'Where To Eat And Drink In... Balham  | Londonist',
    selectedDate: Fri Apr 01 2016 01:00:00 GMT+0100 (BST),
    __v: 0 },
  { _id: 570260738ef368db32c570c9,
    url: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators',
    title: 'Expressions and operators - JavaScript | MDN',
    selectedDate: Sun Apr 10 2016 01:00:00 GMT+0100 (BST),
    __v: 0 },
  { _id: 56fffb8eeb76276c8f39e3f5,
    url: 'https://news.ycombinator.com/item?id=11404770',
    title: 'The Trouble with CloudFlare | Hacker News',
    selectedDate: Sun Apr 03 2016 01:00:00 GMT+0100 (BST),
    __v: 0 },
  { _id: 56fffb6ceb76276c8f39e3f4,
    url: 'http://wellnessmama.com/13700/benefits-coconut-oil-pets/',
    title: 'Benefits of Coconut Oil for Pets - Wellness Mama',
    selectedDate: Sat Apr 02 2016 01:00:00 GMT+0100 (BST),
    __v: 0 } ]

3 个答案:

答案 0 :(得分:2)

我认为问题是.indexOf功能。我假设您正在使用Date个对象。看看这个:

> var x = new Date(2000, 1, 1);
> var y = new Date(2000, 1, 1);
> x === y
false

那是因为这些是不同的对象,即使它们指向同一天。因此.indexOf必须失败,因为它在内部使用===

我认为你必须做更复杂的事情并实际比较日期:

var days = [friday, saturday, sunday];
var theWeekend = results.filter(function(obj) {
    for (var i = 0; i < days.length; i++) {
        var day = days[i];
        // now properly compare the day of week
        if (day.getDay() == obj.selectedDate.getDay()) {
            return true;
        }
    }
    return false;
});

或类似的东西取决于你真正想要的东西。

答案 1 :(得分:1)

如果找不到该项, indexOf 将返回-1。

0 >= -1(找不到该项时的情况)时,您的表达式为 true

这可能就是为什么你没有得到你期待的结果呢?

修改:您可能希望查看阵列的地图过滤器功能。有多个这样的实用程序函数可用,您是否为您的应用程序使用任何JS框架?

答案 2 :(得分:0)

你有几个问题。首先,你的if语句是相反的。它正在推动indexOf返回小于0的所有情况,但是你希望它推动所有大于或等于0的情况。而且,似乎indexOf使用{{1}对象不起作用。对此的一个解决方案是首先将它们转换为整数。

另外,我对你的代码做了一些调整。首先,我只创建一次周末日期数组(您当前正在重复每次迭代)。其次,你的while循环只是一个for循环,所以我会使用一个实际的for循环,因为它会让其他人更容易阅读。

Date