[英]printing the result of the function to the console.
var square = function(x){
return x*x;
}
square(10);//100
var square = function(x){
var total = x*x;
console.log(total);
}
square(10);//second way(probably wrong)
I was reviewing what I once wrote when passing the JS-track on codecademy.com. 我正在回顾在codecademy.com上通过JS跟踪时曾经写过的内容。 The task is incredibly simple - write a function that just squares a number and prints it in the console.
这项任务非常简单-写一个仅对数字取平方并在控制台中打印出来的函数。
I did it the second way (using total variable inside the function block). 我采用第二种方法(在功能块内部使用总变量)。 Now I would do it the first way.
现在,我将以第一种方式进行操作。 Both seem to work.
两者似乎都起作用。 But is the second one really correct?
但是第二个真的正确吗?
Well the first one actually calculates the square root, so it's a usable function. 好吧,第一个实际上是计算平方根,因此这是一个可用的函数。 The second one just prints it to the console - so I'd stick with the first one.
第二个只是将其打印到控制台上-所以我会坚持使用第一个。
The second one is still correct if you want it printed to the console. 如果要将第二个打印到控制台,第二个仍然正确。 In a real-world situation, you'd want the result returned to the calling function so it can do other things with the value and then it would fail, since your function does not return anything.
在实际情况下,您希望将结果返回给调用函数,以便它可以使用该值执行其他操作,然后失败,因为函数不会返回任何内容。
Both methods work at correctly squaring the input, and there's nothing wrong syntactically in either function. 两种方法都可以正确地对输入进行平方运算,并且两个函数在语法上都没有错。
However, there is a problem with practicality. 但是,存在实用性问题。 The first function only calculates the square of the input without giving out any return, or output, and therefore is not useful.
第一个函数仅计算输入的平方而不给出任何返回或输出,因此没有用。
The second function is more practical because it logs the square of the input into the console, and therefore has an output, which in turn can be useful. 第二个功能更为实用,因为它会将输入的平方记录到控制台中,因此具有输出,这反过来可能很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.