问题描述
有什么区别:
function bla1(x){console.log(x)}
和
function bla(x){return console.log(x)}
我应该在哪些情况下使用 return
?
In which cases should I use return
?
此外,当从函数返回一个值时,会发生什么?是存储在某个地方吗?
also, when a value is returned from a function, what happens to it? is it stored somewhere?
推荐答案
第一个函数返回 undefined
(因为它不是 return
任何明确的),第二个返回 console.log
返回。
The first function returns undefined
(as it does not return
anything explicitly), the second one returns whatever console.log
returns.
当函数生成某个值并且您想将其传递回调用者时。以 Math.pow
为例。它需要两个参数,base和exponent,并将引发的基数返回给指数。
When the function is generating some value and you want to pass it back to the caller. Take Math.pow
for example. It takes two arguments, the base and the exponent and returns the base raised to the exponent.
如果要存储返回值,则必须将其分配给变量
If you want to store the return value, then you have to assign it to a variable
var value = someFunction();
这将存储 someFunction
的返回值值
。如果你在没有指定返回值的情况下调用该函数,那么该值就会被静默删除:
This stores the return value of someFunction
in value
. If you call the function without assigning the return value, then the value is just silently dropped:
someFunction();
这些是编程基础知识,不仅与JavaScript的。您应该找到一本介绍这些基础知识的书,尤其是JavaScript,我建议您阅读。也许关于的维基百科文章也很有帮助。
These are programming basics and are not only relevant to JavaScript. You should find a book which introduces these basics and in particular for JavaScript, I recommend to read the MDN JavaScript Guide. Maybe the Wikipedia article about Functions is helpful as well.
这篇关于何时使用return,以及返回的数据会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!