为什么我的代码不起作用?我想,一旦我在日期上使用了getTime(),而不是尝试比较日期就可以了,但是没有用。请帮忙。我也意识到,现在有一个例子可以使这个例子相等,但是对于我的实际项目来说,它可以是相等的,所以请不要免除任何答案。谢谢。
$(document).ready(function() {
$(document).on("scroll", animationDivs);
function animationDivs(event) {
var scrollPos = $(document).scrollTop();
var divs = $("*");
$(divs).each(function() {
var currLink = $(this);
if (currLink.position().top <= scrollPos && currLink.position().top + currLink.height() > scrollPos) {
currLink.style.color = "red";
}
});
};
});
答案 0 :(得分:1)
您的问题是您正在将highDateSoFar
初始化为null
。当您对null进行大于比较时,您将无法获得所需的结果。将初始化更改为var highDateSoFar = -Number.MAX_VALUE
。它将以最低的可能值开始,因此第一次比较肯定是正确的。
var x = new Date(1960,07,16);
var y = new Date(1950,04,28);
var z = new Date(1940,01,07);
var playerData = [
{name: "John", date: x.getTime()},
{name: "Bill", date: y.getTime()},
{name: "Greg", date: z.getTime()},
];
function findHighScore() {
var highDateSoFar = -Number.MAX_VALUE;
var result;
for (var i = 0; i < playerData.length; i++) {
if (playerData[i].date > highDateSoFar) {
result = playerData[i];
highDateSoFar = playerData[i].date;
}
else if (playerData[i].date === highDateSoFar) {
result = 'equal';
}
}
return result;
}
var highPlayer = findHighScore();
var highPlayerName = highPlayer.name;
var highPlayerDate = highPlayer.date;
var highPlayerIndex = playerData.indexOf(highPlayer);
console.log({highPlayer});