我不明白 javascript 中的函数返回

2022-01-19 00:00:00 function return javascript

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

请帮帮我.

解决方案

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

1.返回函数的结果

return 言行一致——它返回一些值给函数调用者

函数 sum(num1, num2) {var 结果 = number1 + number2返回结果}var result = sum(5, 6)//结果现在保存值 '11'

<强>2.停止函数的执行

使用 return 的另一个原因是因为它也中断函数的执行 - 这意味着如果你点击 return,函数停止运行它后面的任何代码.

函数 sum(num1, num2) {//如果缺少 2 个必需参数中的任何一个,则停止如果 (!num1 || !num1) {返回}//并且不要继续下面的返回号码 1 + 号码 2}var result = sum(5)//sum() 返回 false,因为未提供所有参数

<小时><块引用>

我们为什么要使用它?

因为它允许您重用代码.

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

  • 您是否会在每次需要时重新编写公式?
  • 如果您的公式有误怎么办?你会去所有的地方吗编写公式以进行更改的代码?

不-相反,您会将其包装到一个函数中并让它返回结果-因此您只需编写一次公式,然后在任何您想要的地方重复使用它:

函数 getLineDistance(x1, y1, x2, y2) {返回 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);

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

Please help me.

解决方案

Why is it used in a function?

1. To return back the results of the 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. To stop the execution of the function

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);

相关文章