gpt4 book ai didi

javascript - While 循环没有将正确的结果推送到数组

转载 作者:行者123 更新时间:2023-11-28 18:39:17 25 4
gpt4 key购买 nike

我有一个 while 循环,应该迭代数组和 selectedDate 值来确定事件是否会在即将到来的周末发生,但是它没有正确过滤结果,我不确定为什么,一切对我来说看起来都是正确的。 while 循环 是此排序作业的正确工具吗?

功能

  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);
}

[星期五、星期六、星期日] 向控制台提供正确的日期:

[ 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 } ]

最佳答案

我认为问题在于 .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;
});

或者类似的东西,这取决于你真正想要的是什么。

关于javascript - While 循环没有将正确的结果推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36403613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com