为Codecademy编写JavaScript函数

问题描述

花一些时间尝试学习Javascript成为更好的开发人员。这段代码有点问题。

function howOld (age,year) {
  let theCurrentYear = 2020;
  const yearDifference = year - theCurrentYear;
  const newAge = Math.abs(age + yearDifference);
  const positiveNewAge = newAge * -1;
  
  if (newAge > age) {
    return `You will be ${newAge} in the year ${year}`;
  } else if (newAge < 0) {
    return `The year ${year} was ${positiveNewAge} years before you were born`;
  } else if (newAge > 0 && newAge < age) {
    return `You were ${positiveNewAge} in the year ${year}`;
  }
};

console.log(howOld(28,2019));

这是它应该做的:

编写一个函数howOld(),该函数具有两个数字参数,年龄和年份,并返回当年(或即将)该年龄的某人的年龄。处理三种不同的情况:

如果年份是将来的年份,则应返回以下格式的字符串:

“您将在[过去的年份]中成为[计算的年龄]” 如果年份是出生年份,则应返回以下格式的字符串:

“ [过去的年]是您出生前的[计算的年数]年” 如果年份是过去的年份,而不是出生的年份,则应返回以下格式的字符串:

“您在[过去的年份]是[计算年龄]”

我遇到的问题是使newAge为正数,因此我可以将其作为正数传递给字符串。我已经尝试过Math.abs()并将newAge乘以-1,但似乎无法将其更改为正数。

解决方法

感谢@vlaz让我再试一次。这是我再次尝试后得出的答案。

function howOld (age,year) {
  let theCurrentYear = 2020;
  const yearDifference = year - theCurrentYear;
  const newAge = age + yearDifference;
  const positiveNewAge = Math.abs(newAge);
  
  if (newAge > age) {
    return `You will be ${newAge} in the year ${year}`;
  } else if (newAge < 0) {
    return `The year ${year} was ${positiveNewAge} years before you were born`;
  } else if (newAge > 0 && newAge < age) {
    return `You were ${positiveNewAge} in the year ${year}`;
  } else if (year === theCurrentYear) {
    return `You are ${age} in the year ${2020}`;
  }
};

console.log(howOld(28,1991));