为什么要教我编写不带参数的(基本)函数?
function idealSleepHours () {
const idealHours = 8;
return idealHours*7
};
它也可以使用参数。我想念什么吗?
function idealSleepHours (idealHours) {
idealHours = 8;
return idealHours * 7
};
对于一个愚蠢的问题,我感到很抱歉,我是JavaScript(和编程)领域的新人,因此一切对我来说都有些混乱。
编辑:非常感谢您的回答,现在我绝对理解其中的区别。
答案 0 :(得分:1)
在JS中,您可以为参数设置默认值。如果不使用该参数,则将采用默认值。
function idealHours(idealHours=8){
return idealHours*8;
}
console.log("Without parameters",idealHours())
console.log("With parameters",idealHours(3))
答案 1 :(得分:0)
这里的重点总是在构建应用程序时要保持灵活性
///this function will always return the same result
//because you hard coded the variable inside the function
///so essential isn't an ideal design for a function unless
///it made logical since in your application
function idealSleepHours () {
const idealHours = 8;
return idealHours*7
};
/*In the function below you are passing a parameter into the function
which is a better design of a function, creating flexiablity.
but the problem is you again hard coded the value of idealhours in your function
so there is no need to set it to 8 inside the function
*/
function idealSleepHours (idealHours) {
idealHours = 8;///this line should be omitted
return idealHours * 7
};
///making a much better function known as a pure function..
function idealSleepHours (idealHours) {
return idealHours * 7
};
///now you can assign your ideal hours based on any case that might come into mind
idealSleepHours(8)///return 56
idealSleepHours(2)//return 14
idealSleepHours(5)//returns 35