iT邦幫忙

2025 iThome 鐵人賽

DAY 20
0
Modern Web

網頁技術探索:30天的前端學習系列 第 20

Day20 JS 認識與使用函式 function及在函式加入參數

  • 分享至 

  • xImage
  •  

什麼是函式 funciton

簡單來說「函式」指的是將一或多段程式指令包裝起來,可以重複使用,也方便維護。

函式的寫法
function name(params) {
    
}

用 function 做宣告,後面自定義一個名稱,加上小括弧(以後可以放參數用),再把要寫入函式的程式碼用一個大括弧包起來

實際來寫一個練習:

function number() {
    console.log('Tim') //字串要加引號
    console.log(323) //數字不用加引號
}

但這樣只是建立好一個函式而已,不會被執行,若要執行函式,要多寫一行程式碼,會如下呈現:

function number() {
    console.log('Tim') //字串要加引號
    console.log(323) //數字不用加引號  
}

number(); //執行函式

函式可以重複執行,如果要重複執行一樣的函式,只要再打上一樣的指令就可了,如下程式碼:

function number() {
    console.log('Tim') //字串要加引號
    console.log(323) //數字不用加引號    
}

number(); //執行函式
number(); //重複執行函式

函式帶入參數

函式基本寫法:

function number() {
  console.log("Tim"); //字串要加引號
  console.log(323); //數字不用加引號
}
number(); //執行函式

在小括弧中可以帶入參數名稱,一樣是自定義。

練習帶入一個參數:

function math(number) {
  var total = number; //宣告變數的值等於參數
  console.log(total); //驗證結果是變數的名稱,但這邊不是輸入字串,故不用加上引號
}
math(10); //執行函式,並帶入參數

函式 + 參數 + 運算

參數可以帶入兩個、三個甚至無限多,並可以利用變數做加減乘除的方式來做更多元的變化。(變數的加減乘除是:+、-、*、/ )

EX. 加法

function math(numOne, numTwo) {
  var total = numOne + numTwo; //結果為兩個變數相加
  console.log(total); //驗證變數
}
math(10, 25); //執行函式,並帶入參數

上一篇
DAY19 javascript環境設置、認識變數 Variable
系列文
網頁技術探索:30天的前端學習20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言