簡體   English   中英

使用 return 關鍵字而不是僅使用 console.log function 並僅傳遞參數有什么區別?

[英]What is the difference of using the return keyword rather than using just a console.log function and just passing the parameters?

我看過一個教程,其中他制作了一個接受任何數字作為參數的 square() function。 他做的function是這樣的:

 function square(number) { return number * number; }; let number = square(2); console.log(number);

我嘗試通過僅在 function 本身中使用 console.log 來執行相同的 function,如下所示:

 function square(number) { console.log(number * number) }; square(2);

兩種代碼都有效,但我不知道兩者之間的區別。 您能否向我解釋一下使用這兩種方式的問題是什么? 或者更好的是,請提供我可以使用的關於我的詢問的任何閱讀材料。

return 語句允許您將 output 分配給變量。 例如:

 function square(number) { return number * number; }; let a = square(3); // assigns 9 to variable a. let b = square(4); // assigns 16 to variable b. let c = a + b; console.log(c); // prints 25.

通過使用return關鍵字,您可以將數據發送回 function 的原始調用者。 例如,讓我們考慮您的兩個代碼塊:

function square(number) {
   return number * number;
};

const sq = square(5);
console.log(sq); // 25

現在,考慮我們是否在 function 本身內部調用console.log

function square(number) {
   console.log(number * number)
};

const sq = square(5);
console.log(sq); // undefined

什么return語句使我們能夠使 function 像呼叫和響應一樣:提出問題,得到答案。 當您需要更復雜的代碼時,這可能很有用。 例如,這是一個添加平方數的示例。


function square(number) {
   return number * number;
};

const a = square(5);
const b = square(10);

console.log(a + b);

以前的 function 無法進行這種操作

這兩個函數的區別如下:

第一個 function 遵循以下簡單步驟:

  1. 調用值為 2 的 function
  2. 乘以 2 * 2
  3. 將值發送回調用 function 的行,在本例中為 4
  4. 將從 function 返回的值 (4) 保存到稱為“數字”的變量中
  5. 將數字 (4) 的值顯示到控制台
  6. 結束 function

第二個 function 做了更多的事情:

  1. 調用值為 2 的 function
  2. 顯示 (2 * 2) 的值
  3. 結束 function

第一個 function 允許我們使用 function 之外的數字。 So we can then maybe pass number back into the function to get a value of 8, while in the second function the value of 4 never leaves the scope of the function.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM