# 章序号/节序号/节/笔记序号 codecademy,function # 概念阐释 # 举例子 # 类比、比较与对比 # 问题 - 用extra practice 写: Sleep Debt Calculator Did you know that giraffes sleep [4.6 hours a day](https://en.wikipedia.org/wiki/Giraffe#Legs,_locomotion_and_posture)? We humans need more than that. If we don’t sleep enough, we accumulate sleep debt. In this project we’ll calculate if you’re getting enough sleep each week using a sleep debt calculator. The program will determine the actual and ideal hours of sleep for each night of the last week. Finally, it will calculate, in hours, how far you are from your weekly sleep goal. If you get stuck during this project or would like to see an experienced developer work through it, click “**Get Unstuck**“ to see a **project walkthrough video**. ### Tasks 12/12 Complete Mark the tasks as complete by checking them off **1-3 实际每天睡眠多少小时?** 1. The first problem to solve is determining how many hours of sleep you got each night of the week. You can create a function that returns any given night’s number of hours of rest. Instead of writing seven different functions (one for each day of the week), let’s write one function with a parameter for the day. Create a function named `getSleepHours` with a single parameter named `day`. Hint For a function with a single parameter, the syntax looks like this: ``` const exampleName = exampleParameter => { }; ``` 2. The function should accept a day as an argument and return the number of hours you slept that night. For instance, if you got 8 hours of sleep on Monday night, calling `getSleepHours('monday')` should return `8`. Use an `if/else` or `switch` statement to implement this. Hint ``` const getSleepHours = day => {  if (day === 'monday') {    return 8;  } else if (day === 'tuesday') {    // continue else if's...  }}; ``` 3. Test the function by calling it multiple times and printing the results to the console. You can remove the tests when you know your function works. --- 计算睡眠欠债,需要计算3件事 - 实际睡眠时间的加总 - 希望睡眠时间的加总 - 计算差值 4. Now that you’ve written a function to get the sleep hours for each night, we need to do three things: - Get the total sleep hours that you actually slept - Get the ideal sleep hours that you prefer - Calculate the sleep debt, if any. To get the total sleep hours that you actually slept, create a new function named `getActualSleepHours` that takes no parameters. Stuck? Get a hint 5. Inside the `getActualSleepHours()` function, call the `getSleepHours()` function for each day of the week. Add the results together and return the sum using an implicit `return`. Hint The concise body form of a function uses arrow notation and does not include brackets or the `return` keyword. ``` const getActualSleepHours = () => getSleepHours('Monday') + getSleepHours('Tuesday') + getSleepHours('Wednesday') + ...; ``` 6. 每天理想睡眠时间x7,并且让理想时间可调整 To get the ideal sleep hours that you prefer, create a function named `getIdealSleepHours` with no parameters. Inside the function, declare a variable named `idealHours` and set its value to your ideal hours per night. Then `return` the `idealHours` multiplied by 7. You’ll want to multiply by 7 to get the total hours you prefer per week. Hint ``` const getIdealSleepHours = () => {  const idealHours = 7.5;  return idealHours * 7;}; ``` 7. Test your two new functions by calling them and printing the results to the console. You can remove the tests when you know your functions works. Hint ``` console.log(getActualSleepHours()); // should print the sum of all sleep hours in the week console.log(getIdealSleepHours()); // if idealHours is 8, should print 56 ``` --- 8. 计算差值 Now that you can get the actual sleep hours and the ideal sleep hours, it’s time to calculate sleep debt. Create a function named `calculateSleepDebt` with **no parameters**. Inside of its block, create a variable named `actualSleepHours` set equal to the `getActualSleepHours()` function call. Then, create another variable named `idealSleepHours`, set equal to the `getIdealSleepHours()` function call. Stuck? Get a hint 9. Now that you have `actualSleepHours` and `idealSleepHours`, you can write a few `if`/`else` statements to output the result to the console. The function should fulfill this logic: - If actual sleep equals ideal sleep, log to the console that the user ==got the perfect amount of sleep==. - If the actual sleep is greater than the ideal sleep, log to the console ==that the user got more sleep than needed==. - If the actual sleep is less than the ideal sleep, log to the console that==the user should get some rest==. Hint `actualSleepHours` must be equal to, greater than, or less than `idealSleepHours`. The `if` and `else if` statements cover the first two cases, and the `else` statement covers the ‘less than’ case. ``` if (actualSleepHours === idealSleepHours) {  console.log('...');} else if (actualSleepHours > idealSleepHours) {  console.log('...');} else {  console.log('...');} ``` 10. 增加可读性,告诉读者少了几个小时的睡眠? To make this calculator more helpful, add the hours the user is over or under their ideal sleep in each log statement in `calculateSleepDebt()`. Hint You can interpolate the math inside the string passed to `console.log()` to print. For instance, if the user got less sleep than is ideal, you could write: ``` if (actualSleepHours < idealSleepHours) {  console.log('You got ' + (idealSleepHours - actualSleepHours) + ' hour(s) less sleep than you needed this week. Get some rest.');} ``` 11. On the last line of the program, start the program by calling the `calculateSleepDebt()` function. Stuck? Get a hint 12. For extra practice, try these: - **不调用getSleepHours(),直接相加7天的睡眠时间**, `getActualSleepHours()` could be implemented without calling `getSleepHours()`. Use literal numbers and the `+` operator to rewrite `getActualSleepHours()`. It should still return the total actual hours slept in the week. - **给理想睡眠时间添加行参** Some people need to sleep longer than others. Rewrite `getIdealSleepHours()` so that you can pass it an argument, like `getIdealSleepHours(8)` where `8` is the ideal hours per night. Update the call to `getIdealSleepHours()` in `calculateSleepDebt()` too. Hint Put the daily sleep hours directly into `getActualSleepHours()`. ``` const getActualSleepHours = () => 6 + 7 + 9 + 8 + 5 + 10 + 11; ``` Make `idealHours` a parameter and multiply it by `7`. ``` const getIdealSleepHours = idealHours => idealHours * 7; ``` When you call the updated function in `calculateSleepDebt()`, call it like this: ``` const calculateSleepDebt = () => {  ...   const idealSleepHours = getIdealSleepHours(8);   ...}; ``` To see the solutions, open the hint. # 问题答案 ```js function getSleepHours(day){ switch(day){ case 'monday': return 8; case 'tuesday': return 7; break; case 'wednesday': return 8; break; case 'thursday': return 5; break; case 'friday': return 7; break; case 'saturday': return 9; break; case 'sunday': return 9; break; default: return 'errors' break; } }; // console.log(getSleepHours('tuesday')); 测试用 function getActualSleepHours(){ let sumOfActualSleepHours = getSleepHours('monday')+getSleepHours('tuesday')+getSleepHours('wednesday')+getSleepHours('thursday')+getSleepHours('friday')+getSleepHours('saturday')+getSleepHours('sunday'); return sumOfActualSleepHours; }; // console.log(getActualSleepHours()); 测试实际睡眠总数 function getIdealSleepHours(ideaHours=8){ return ideaHours*7; } // console.log(getIdealSleepHours()); 测试理想睡眠总数 function calculateSleepDebt (){ let ActualSleepHours = getActualSleepHours(); let IdealSleepHours = getIdealSleepHours(); if(ActualSleepHours===IdealSleepHours){ return 'got the perfect amount of sleep'; }else if(ActualSleepHours > IdealSleepHours){ return 'the user got more sleep than needed'}else if(ActualSleepHours < IdealSleepHours){ return `you got ${IdealSleepHours-ActualSleepHours} hours less than you need this week, you should get some rest.` } }; console.log(calculateSleepDebt ()); ``` # 备注(经验集/错误集) ## 经验集 ## 错误集 ## 参考资料