JavaScript 函式需要返回一個值嗎?
JavaScript 函式可以有可選的 return 語句,即可以選擇返回一個值。此語句應是函式中的最後一條語句。
例如,可以在函式中傳遞兩個數字,然後讓函式將它們的乘積返回到呼叫程式。
示例
嘗試以下示例。它定義了一個函式,該函式將兩個引數進行連線,然後在呼叫程式中返回結果。
<html> <head> <script type = "text/javascript"> function concatenate(first, last){ var full; full = first + last; return full; } function secondFunction(){ var result; result = concatenate('John', 'Doe'); document.write (result ); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type = "button" onclick = "secondFunction()" value = "Call Function"> </form> <p>Use different parameters inside the function and then try...</p> </body> </html>
廣告