简体   繁体   English

为什么我需要在 function 结束之前放置一个 return 语句?

[英]why do I need to put a return statement right before a function ends?

function getPizzaCost(size, nTopping) {
  let cost = 10; // base cost for a small pizza
  if(size === "medium") {cost += 4;}
  else if(size === "large") {cost += 8;}
  cost += nTopping;
}

let pizzaSize = "medium";
let numToppings = 19;

let cost = getPizzaCost(pizzaSize, numToppings);
console.log("cost " + cost + "$")

I know I'm supposed to put a return cost right below the cost += nToppings but why do I need to do that?我知道我应该把退货成本放在成本 += nToppings 的正下方,但为什么我需要这样做? is there a specific reason for that?有什么具体原因吗? I've search up why we needed it but it got a little confusing我已经搜索了为什么我们需要它,但它有点令人困惑

That is because cost is a local variable to that function and the value of it is not accessible from outside.这是因为cost是 function 的局部变量,它的值不能从外部访问。 So the return statements gives back the value of cost once the function is executed.因此,一旦执行 function,return 语句就会返回cost值。

You can also declare it outside and use that, but that variable will be avaialble to be used by other function which will give an erroneous result.您也可以在外部声明并使用它,但该变量将可供其他 function 使用,这将给出错误结果。

A function without return keyword, it will automatically return undefined.一个 function 没有 return 关键字,它会自动返回 undefined。

Why do you need to return cost?为什么需要退货费用?

 function getPizzaCost(size, nTopping) { let cost = 10; // base cost for a small pizza const randomVar = "random" if(size === "medium") {cost += 4;} else if(size === "large") {cost += 8;} cost += nTopping; }

In the function above how does js know what variable it need to return, so, if you want get cost variable value you need to return cost .在上面的 function 中,js 是如何知道需要返回什么变量的,所以,如果要获取cost变量值,则需要return cost

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM