[英]Why the console.log prints to the console "undefined" when I try to add some results in the function?
I try to add getSleepHours() in the const getActualSleepHours() to have a sum.我尝试在 const getActualSleepHours() 中添加 getSleepHours() 以获得总和。 But the console.log prints undefined and I don't know what I'm doing wrong.
但是 console.log 打印 undefined ,我不知道我做错了什么。 Could anyone help me?
有人可以帮助我吗?
const getSleepHours = day => { switch(day) { case 'monday': return 8; break; case 'tuesday': return 8; break; case 'wednesday': return 9; break; case 'thursday': return 9; break; case 'friday': return 7; break; case 'saturday': return 10; break; case 'sunday': return 9; break; } }; const getActualSleepHours = () => { getSleepHours('monday') + getSleepHours('tuesday') + getSleepHours('wednesday') + getSleepHours('thursday') + getSleepHours('friday') + getSleepHours('saturday') + getSleepHours('sunday'); }; const getIdealSleepHours = () => { const idealHours = 8.5; return idealHours * 7; }; console.log(getActualSleepHours()); console.log(getIdealSleepHours());
You missed the return, the function you're calling has no return value so it returns what every executed JS function with no return value returns, undefined
您错过了返回,您调用的函数没有返回值,因此它返回每个执行的 JS 函数没有返回值返回的内容,
undefined
const getSleepHours = day => { switch(day) { case 'monday': return 8; break; case 'tuesday': return 8; break; case 'wednesday': return 9; break; case 'thursday': return 9; break; case 'friday': return 7; break; case 'saturday': return 10; break; case 'sunday': return 9; break; } }; const getActualSleepHours = () => getSleepHours('monday') + getSleepHours('tuesday') + getSleepHours('wednesday') + getSleepHours('thursday') + getSleepHours('friday') + getSleepHours('saturday') + getSleepHours('sunday'); const getIdealSleepHours = () => { const idealHours = 8.5; return idealHours * 7; }; console.log(getActualSleepHours()); console.log(getIdealSleepHours());
You're not returning anything in your getActualSleepHours
function.您没有在
getActualSleepHours
函数中返回任何内容。 Get rid of the braces so it goes from摆脱大括号,所以它从
const getActualSleepHours = () => {
getSleepHours("monday") +
getSleepHours("tuesday") +
getSleepHours("wednesday") +
getSleepHours("thursday") +
getSleepHours("friday") +
getSleepHours("saturday") +
getSleepHours("sunday");
};
to到
const getActualSleepHours = () =>
getSleepHours("monday") +
getSleepHours("tuesday") +
getSleepHours("wednesday") +
getSleepHours("thursday") +
getSleepHours("friday") +
getSleepHours("saturday") +
getSleepHours("sunday");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.