JavaScript - Function(函式)介紹(一)

JavaScript - Function(函式)介紹

function 函式可重複使用,藉由這方式可讓程式碼增加可讀性。

  • function 關鍵字代表一個函式
  • setName  代表函式名稱(駝峰式)
  • name,age 代表引數,可傳入函式使用 當函式被呼叫用時就會傳遞值。
function setName(name, age) {
      
    if (age < 30) { //如果age < 30
        console.log("My Name is..." + name + "  " + "My Age Is..." + age);
    } else {  //age > 30
        console.log("My Name is..." + name + "  " + "My Age Not Is..." + age);
    }
}

setName("kelly", 15);  //"My Name is...kelly  My Age Is...15"

setName("Frances", 35);//"My Name is...Frances  My Age Not Is...35"

setName("Ray", 33);    //"My Name is...Ray  My Age Not Is...33"

 

如圖 設setName("kelly" , 15 ); 這時引數裡的age 對應引數15作為判斷,若 15 < 30  則會得到"My Name is...kelly  My Age Is...15"(因為age==15成立了age< 30) 若不成立則出現My Name is...kelly My Age Not Is...15。

  • 引數可使用字串,布林值,數字等
  • 可以使用變數當引數傳入