![](/img/trans.png)
[英]I don't understand this javascript function call and where it would be used
[英]I don't understand function return in javascript
任何人都可以解釋為什么在函數中使用javascript return語句? 何時以及為什么要使用它?
請幫我。
為什么在函數中使用它?
1.返回函數的結果
返回執行的操作 - 它將一些值返回給函數調用者
function sum(num1, num2) {
var result = number1 + number2
return result
}
var result = sum(5, 6) // result now holds value '11'
2.停止執行該功能
使用return
另一個原因是因為它也會中斷函數的執行 - 這意味着如果你點擊return
,函數就會停止運行它后面的任何代碼。
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
我們為什么要使用它?
因為它允許您重用代碼。
例如,如果您正在編寫一個執行幾何計算的應用程序,那么您可能需要計算2點之間的距離 ; 這是一個常見的計算方法。
不 - 相反,你將它包裝成一個函數並讓它返回結果 - 所以你編寫一次公式,然后你可以在任何地方重復使用它:
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);
您使用return語句有兩個原因:
從函數返回特定值。
在函數的最后一行代碼之前完成函數的執行。
沒有任何return value;
聲明,該函數不返回特定值(技術上返回值undefined
)。
如果函數中沒有特定的return語句,函數將一直運行到函數中的最后一行代碼。
例子:
function add(x, y) {
// return a sum of the two arguments
return x + y;
}
console.log(add(1, 3)); // 4
function findParm(str, key) {
if (!str || !key) {
// invalid parameters, so return null
return null;
}
var pieces = str.split("&");
for (var i = 0; i < pieces.length; i++) {
var loc = str.indexOf(pieces[i] + "=");
if (loc >= 0) {
// when we've found a match, return it and finish execution of the function
return str.slice(loc + key.length + 1);
}
}
// no match found, return null
return null;
}
var str = "user=John&login=yes"
findParam(str, "login"); // "yes"
它用於從函數返回一個值。
假設您想要一個函數來進行一些計算......例如,計算一個div框在瀏覽器屏幕上的左側位置。
你調用函數並給它html選擇器,然后函數'返回'左邊的位置值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.