JavaScript 返回值
我正在学习 JavaScript 作为我的第一语言,我在这里得到了函数的想法,但我不明白最后的返回值的意义是什么。
它有什么用?
I'm learning JavaScript as my first language and I'm getting the idea here as far as functions go but I don't understand what the point of the return value at the end is.
What is it used for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简而言之,返回一个值,以便您可以在程序的其他地方使用它。考虑以下(毫无意义的)函数:
当您调用该函数时,您提供 2 个参数
x
和y
。函数体将它们相加并返回结果。您可能希望能够使用结果,因此当您调用该函数时,您可以将结果分配给一个变量:现在您已经添加了一个变量,其中包含调用该函数的结果,您可以可以在该变量的包含范围内的任何其他地方使用它。这意味着您不必每次想要使用它的结果时都一遍又一遍地调用
addNumbers(5, 10)
。To put it simply, a value is returned so you can use it elsewhere in your program. Consider the following (pretty pointless) function:
When you call that function, you supply 2 arguments
x
andy
. The function body adds those together and returns the result. You probably want to be able to use the result, so when you call the function you can assign the result to a variable:And now that you have a variable
added
with the result of calling the function, you can use that anywhere else in the containing scope of that variable. That means you don't have to calladdNumbers(5, 10)
over and over again every time you want to use the result of it.返回值被传递回调用函数的地方。
The return value is passed back to whatever called the function.
返回 Stamenet 完成该方法并返回调用者的值。
The return stamenet finish the method and returns the value for the caller.
函数执行某种任务。有时您需要查看任务的结果,有时则不需要。例如,运行此代码:
multiply() 的返回值(在本例中为“4”)将成为alert() 函数的参数。因此,此代码将显示一个警告框,其中包含数字 4。
A function performs a task of some sort. Sometimes you need to see the result of a task, and sometimes you don't. Run this code for example:
The return value of multiply() (in this case "4") will become the argument of the alert() function. This code will therefore show an alert box with the number 4 in it.