何时使用return,以及返回的数据会发生什么? [英] When to use return, and what happens to returned data?

查看:129
本文介绍了何时使用return,以及返回的数据会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别:

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?

推荐答案


有什么区别

What is the difference

第一个函数返回 undefined (因为它不是 return 任何明确的),第二个返回 console.log 返回。

The first function returns undefined (as it does not return anything explicitly), the second one returns whatever console.log returns.


在哪些情况下我应该使用return?

In which cases should I use return?

当函数生成某个值并且您想将其传递回调用者时。以 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.


当从函数返回一个值时,会发生什么事?是存储在某个地方吗?

When a value is returned from a function, what happens to it? is it stored somewhere?

如果要存储返回值,则必须将其分配给变量

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,我建议您阅读 MDN 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,以及返回的数据会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆