邂逅Javascript

Lesson 6 :  Functions 函數

什麼是函數(function)?

y = f(x)

input

5

f(x)

output

20

y = function(x)

input

 

黑盒子

output

做某些事情

function f(x){
    return x*4;
}

console.log(f(5)); //20
console.log(f(1)); //4

function isFail(score){
    if(score>=60){
        return false;
    }else{
        return true;
    }
}
console.log(isFail(65)); //false

function isPass(score){
    return score>=60;
}
console.log(isPass(59)); //false

function 名字(參數){
    //do something
    return 結果;
}
function add(a, b){
  return a+b;
}
console.log(add(2,5)) //7

function max(numberA, numberB){
  if(numberA>numberB){
    return numberA;
  }else{
    return numberB;
  }
}
console.log(max(10,20)); //20

function log(str){
  console.log(str);
}
log('test'); //test

跟函式有關的用法

arguments:傳進來的參數陣列

function add(){
  var total = 0;
  for(var i=0;i<arguments.length;i++){
    total+=arguments[i];
  }
  return total;
}
console.log(add(1,2,3)); //6
console.log(add(1,2,3,4,5,100)); //115

跟函式有關的用法

apply與call:呼叫函式

function add(){
  var total = 0;
  for(var i=0;i<arguments.length;i++){
    total+=arguments[i];
  }
  return total;
}

console.log(add.apply(null, [1, 2, 3])); //6
console.log(add.call(null, 1, 2, 3)); //6

另一種函式宣告

var add = function(a, b){
  return a+b;
}
console.log(add(1,2)); //3
console.log(typeof(add)) //function

匿名函式(Anonymous function)

function execute(num, fn){
  console.log(fn(num));
}

var triple = function(num){
  return num*3;
}

execute(10,triple);

execute(10, function(a){
  return a*3;
});



遞迴(recursion)

/*
費式數列:f(n) = f(n-1) + f(n-2)
f(0) = 1;
f(1) = 1;
1, 1, 2, 3, 5, 8, 13, ....
*/

function fib(n){
  if(n<=1){
    return 1;
  }else{
    return fib(n-1)+fib(n-2);
  }
}
console.log(fib(5));
function fib(n){
  if(n<=1){
    return 1;
  }else{
    return fib(n-1)+fib(n-2);
  }
}
console.log(fib(5));

fib(5) -> return fib(4)     +         fib(3)
                   |                    |
            fib(3) + fib(2)          fib(2)  +  fib(1)
             |         |              |          |
      fib(2)+fib(1) fib(1)+fib(0) fib(1)+fib(0)  1
       |       |     |      |      |      |
fib(1)+fib(0)  1     1      1      1      1
  |     |
  1     1

HW #5

請寫一個函式

當輸入是1時,輸出*

當輸入是2時,輸出**

當輸入是3時,輸出***

...

當輸入是10時,輸出**********

hint:

function print_star(n){

  ....

}

HW #5

有個東西叫做階乘(factorial)

1! = 1

2! = 1*2 = 2

3! = 1*2*3 = 6

4! = 1*2*3*4 = 24

請寫出能夠計算階乘的函式

console.log( f(5) ); // 120

參考解答

 

function f(n){
  if(n==1){
    return 1;
  }
  return n*f(n-1);
}

console.log(f(5));

To iterate is human, to recursive, divine! 

遞迴只應天上有,凡人應當用迴圈

function f(n){
  var total = 1;
  for(var i=1;i<=n;i++){
   total*=i;
  }
  return total;
}

console.log(f(5));

邂逅Javascript - Lesson 6 : Functions 函數

By huli

邂逅Javascript - Lesson 6 : Functions 函數

  • 387
Loading comments...

More from huli