首页 > 解决方案 > 如果带有 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.
*/  

标签: javascript

解决方案


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


推荐阅读