javascript - 如果带有 ageDifference 的语句未正确计算最接近的年龄
问题描述
当我试图找到年龄与 Sonya Sotomayor 最接近的人时,出了点问题。任何人都可以检测到我的错误吗?
var notablePeople = {
"Elvis Presley": new Date(1935, 0, 8),
"Sonya Sotomayor": new Date(1954, 5, 25),
"Franklin D. Roosevelt": new Date(1882, 0, 30),
"Ben Carson": new Date(1951, 8, 18),
"Roger Staubach": new Date(1942, 1, 5),
"Steve Jobs": new Date(1955, 1, 24),
"Albert Einstein": new Date(1879, 2, 14),
"Isaac Asimov": new Date(1919, 9, 4),
"Jada Pinkett Smith": new Date(1971, 8, 18),
"Grace Hopper": new Date(1906, 11, 9),
"Jared Nicholas": new Date(1995, 5, 16)
};
// Find who is closest in age to Sonya Sotomayor
var sonyaAge = notablePeople["Sonya Sotomayor"].getTime();
var ageDifference = Infinity;
var personClosest = "";
for (person in notablePeople) {
// See if this person's age difference is closer
if (person != "Sonya Sotomayor" && Math.abs(notablePeople[person].getTime() - sonyaAge) < ageDifference) {
ageDifference = Math.abs(notablePeople[person].getTime() - sonyaAge);
ageDifference = ageDifference / 1000 / 60 / 60 / 24 / 365;
personClosest = person;
}
}
console.log("\nClosest age difference is " + person + " with " + ageDifference + " years difference.");
输出:
/*This is not correct
Closest age difference is Jared Nicholas with 19.473858447488585 years difference.
*/
解决方案
var notablePeople = {
"Elvis Presley": new Date(1935, 0, 8),
"Sonya Sotomayor": new Date(1954, 5, 25),
"Franklin D. Roosevelt": new Date(1882, 0, 30),
"Ben Carson": new Date(1951, 8, 18),
"Roger Staubach": new Date(1942, 1, 5),
"Steve Jobs": new Date(1955, 1, 24),
"Albert Einstein": new Date(1879, 2, 14),
"Isaac Asimov": new Date(1919, 9, 4),
"Jada Pinkett Smith": new Date(1971, 8, 18),
"Grace Hopper": new Date(1906, 11, 9),
"Jared Nicholas": new Date(1995, 5, 16)
};
// Find who is closest in age to Sonya Sotomayor
var sonyaAge = notablePeople["Sonya Sotomayor"].getTime();
var ageDifference = Infinity;
var personClosest = "";
for (person in notablePeople) {
// See if this person's age difference is closer
console.log(person,Math.abs(notablePeople[person].getTime() - sonyaAge) / 1000 / 60 / 60 / 24 / 365);
if (person != "Sonya Sotomayor" && (Math.abs(notablePeople[person].getTime() - sonyaAge) < ageDifference)) {
ageDifference = Math.abs(notablePeople[person].getTime() - sonyaAge);
personClosest = person;
}
}
ageDifference = ageDifference / 1000 / 60 / 60 / 24 / 365;
console.log("\nClosest age difference is " + personClosest + " with " + ageDifference + " years difference.");
//您以错误的格式比较年龄,并且您使用的是 person 而不是 personClosest
推荐阅读
- webpack - 如何将 sass 文件导出到 dist 文件夹保留文件夹结构?
- class - 获取其他类的字符串(颤振)
- java - 我的 java 程序没有将正确的项目放入输出数组
- c# - 如何在 asp.net core services.AddCors 中使用 * 关键字
- angular - onsameurlnavigation 'reload' 不能以角度工作
- c# - 如何在 AWS 窗口服务器中运行 Windows 自动化应用程序
- dart - vs code 1.47.1 自动重新格式化dart代码文件
- excel - 您可以将在 Excel 中创建的形状分组吗?
- postgresql - 为地理类型添加唯一约束
- html - 有什么更好的方法来创建这种可以在多个设备上保持响应以及使用 twitter 引导程序的精确布局?