我正在使用codecademy学习JS,并且通过此函数调用获得的间歇性结果。在某些情况下,它可以正确显示,但是如果我继续重新运行该程序,则在所调用的日期中它将输出未定义的内容。我在做什么错了?
James的活动是:5K
詹姆斯的训练时间是:不确定的天数
帕特拉的活动是:骑自行车
埃及艳后的训练时间是40天
Frederick的事件是:5K
弗雷德里克的训练时间是:未定义的天数
const getRandomEvent = () => {
let random = Math.floor(Math.random() * 3)
if(random === 0){
return "a 5K"
}
else if(random === 1){
return "Cycling"
}
else if(random === 2)
return "Marathon"
}
const getTrainingDays = event =>{
let days;
if(event === "5K"){
days = 60;
}
else if(event === "Cycling"){
days = 40;
}
else if(event === "Marathon"){
days = 250;
}
return days;
}
const event = getRandomEvent();
const days = getTrainingDays(event);
const event2 = getRandomEvent();
const days2 = getTrainingDays(event2);
const event3 = getRandomEvent();
const days3 = getTrainingDays(event3);
const logEvent = (name, event) => console.log(`${name}'s event is: ${event}`);
const logTime = (name, days) => console.log(`${name}'s training time is: ${days} days`);
logEvent("James", event);
logTime("James", days);
logEvent("Cleopatra", event2);
logTime("Cleopatra", days2);
logEvent("Frederick", event3);
logTime("Frederick", days3);
答案 0 :(得分:0)
用于获取事件的函数将为a 5K
返回random === 0
,但是getTrainingDays
检查event === 5K
。
修复脚本以检查事件a 5K
。
您还应在适当的地方添加一个catch all else语句。
请考虑以下内容:
const getRandomEvent = () => {
let random = Math.floor(Math.random() * 3);
if (random === 0) {
return "a 5K"
} else if (random === 1) {
return "Cycling"
} else if(random === 2) {
return "Marathon"
}
}
const getTrainingDays = event => {
let days;
if (event === "a 5K") {
days = 60;
} else if (event === "Cycling") {
days = 40;
} else if (event === "Marathon") {
days = 250;
} else {
days = -1;
}
return days;
}