[JS101] JavaScript - Function


Posted by yymarlerr on 2021-05-14

function() {}

  • 範例
    function star(a, b, c) {
    return a + 2*b + 3*c
    }
    console.log(star(1, 2, 3))
    
  • 可以 return 物件,唯大括號要接在 return 後方,不然會回傳 undefined
    function box(x){
      return{
        answer: x*2
        }
    }
    
  • 範例二
    function speed(min, max) {
      var result = []
      for(var i = min; i<=max; i++){
        result.push(i)
      }
      return result
    }
    var a = 3
    var b = 10
    console.log(function speed(a, b))
    
  • function 裡面的參數也可用變數
  • 不一定要加參數

function 和 return 的差別

參考

宣告函式的不同種方式

  • function hello(){
    console.log('hello')
    }
    
  • var hello = function() {
    console.log('hello')
    }
    
  • 這個 function 的名稱是由變數決定

  • function print(anything) {
    anything()
    }
    function hello() {
    console.log('hello')
    }
    print(hello)
    
  • 傳 function 進去 function

  • 匿名函式(沒有名字的函式)

參數 parameter

  • function (<參數>)

引數 argument

  • 真正傳進去的東西
  • 舉例如下,2 和 3 就是引數
function twice(a, b){
  return a+b
}
function twice(2, 3)
  • 引數也可用 argument 來表示
function add(){
  return arguments [0] + arguments [1]
}

console.log(add(2, 5))
  • argument 長得很像陣列的物件
    • arguments[a]

      => 回傳 5
    • arguments

      => 回傳 [Arguments] { '0': 2, '1': 5 }









Related Posts

MSSQL 的觸發程序 TRIGGER

MSSQL 的觸發程序 TRIGGER

程式基礎

程式基礎

第五天:爬蟲【三】

第五天:爬蟲【三】


Comments