網頁全端開發JavaScript_0922

認識函式


定義

                    function 函式名稱 (參數) {
                        執行內容
                    }                    
                
                    function money (price1, price2, discount) {
                        let result = price1 + price2 - discount 
                    
                        return result
                    }                    
                

呼叫

                    函式名稱 (  )                  
                
                    let tank = money (100,200,50)
                    let ella = money (200,300,100)
                    console.log('total',ella);                            
                

return

  • 使用位置只能在function裡,執行完函式交出結果
  • 執行return後會跳出該函式,下方程式不會被執行
  • 用 return 回傳空值也具有「中止」程式碼的功能
  • 若需要對function所回傳的值做後續的處理,那麼就必須要return回傳值

console.log

  • 使用位置不限於function裡
  • 用來debug或檢視目前的計算結果、狀態…等等

注意

  • 在function中若沒有return語句,function會回傳undefined (默認的回傳值)
  • 每個function 都視為1個物件