花一些时间尝试学习 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(),它有两个数字参数:age 和 year,并返回当前处于该年龄的人在该年已经(或将要)的年龄。处理三种不同的情况:
如果年份是未来,则应返回以下格式的字符串:
'You will be [calculated age] in the year [year passed in]' 如果年份是他们出生之前的年份,则应返回以下格式的字符串:
'The year [year passed in] is [calculated number of years] before you'rebirth' 如果年份是过去但不在此人出生之前,则应返回以下格式的字符串:
'你是 [计算年龄] 在 [过去的年份]'
我遇到的问题是让 newAge 成为一个正数,这样我就可以将它作为一个正数传递给字符串。我已经尝试过 Math.abs() 并将 newAge 乘以 -1,但我似乎无法让它变为正数。