# 邂逅Javascript

Lesson 6 :  Functions 函數

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;
}

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];
}
}

## 跟函式有關的用法

apply與call：呼叫函式

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

## 另一種函式宣告

``````var add = function(a, b){
return a+b;
}

## 匿名函式(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(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

...

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;
}
}

console.log(f(5));
``````

By huli

• 387