我不明白javascript中的函数返回 [英] I don't understand function return in javascript

查看:64
本文介绍了我不明白javascript中的函数返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释为什么在函数中使用javascript return语句?什么时候以及为什么要使用它?

Can anyone explain why javascript return statement is used in function? when and why we should use it?

请帮助我.

推荐答案

为什么要在函数中使用它?

Why is it used in a function?

1.返回函数结果

return执行所说的操作-将 returns 返回一些值到 function调用程序

The return does what is says - it returns back some values to the function caller

function sum(num1, num2) {
  var result = number1 + number2

  return result
}

var result = sum(5, 6) // result now holds value '11'

2.停止执行功能

使用return的另一个原因是因为它还会中断该函数的执行-这意味着,如果您按下return,该函数就会停止运行任何紧随其后的代码.

Another reason that return is used is because it also breaks the execution of the function - that means that if you hit return, the function stops running any code that follows it.

function sum(num1, num2) {
  // if any of the 2 required arguments is missing, stop
  if (!num1 || !num1) {
    return
  }

  // and do not continue the following

  return number1 + number2
}

var result = sum(5) // sum() returned false because not all arguments were provided


为什么要使用它?

Why we should use it?

因为它允许您重用代码.

Because it allows you to reuse code.

例如,如果您正在编写一个进行几何计算的应用程序,则可能需要计算两个点之间的距离;这是一个常见的计算.

If for example you're writing an application that does geometric calculations, along the way you might need to calculate a distance between 2 points; which is a common calculation.

  • 您是否会在每次需要时再次编写公式 ?
  • 如果您的公式有误怎么办?您可以访问所有地点中的 公式写在哪里进行更改的代码?
  • Would you write the formula again each time you need it?
  • What if your formula was wrong? Would you visit all the places in the code where the formula was written to make the changes?

否-相反,您可以将其包装到函数中并让其返回结果-因此,您只需编写一次公式,即可在需要的地方重复使用它:

No - instead you would wrap it into a function and have it return back the result - so you write the formula once and you reuse it everywhere you want to:

function getLineDistance(x1, y1, x2, y2) {
  return Math.sqrt((Math.pow((x2 - x1), 2)) + (Math.pow(( y2 - y1), 2)))
}

var lineDistance1 = getLineDistance(5, 5, 10, 20); 
var lineDistance2 = getLineDistance(3, 5, 12, 24);

这篇关于我不明白javascript中的函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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