# 函式宣告

js> function max(num1, num2) {
>     return num1 > num2 ? num1 : num2;
> }
js> max(10, 5);
10
js>

js> function func(a, b) {
>     print(a);
>     print(b);
> }
js> func(10, 20);
10
20
js> func(10);
10
undefined
js> func();
undefined
undefined
js> func(10, 20, 30, 40);
10
20
js>

js> function sum() {
>     var sum = 0;
>     for(var i = 0; i < arguments.length; i++) {
>         sum += arguments[i];
>     }
>     return sum;
> }
js> sum(1, 2);
3
js> sum(1, 2, 3);
6
js> sum(1, 2, 3, 4);
10
js>

arguments不是Array實例，它只是具有數字作為特性，特性參考至傳入的引數，並具有length特性代表傳入引數的個數

js> function func(a, b) {
>     print(a + ': ' + arguments[0]);
>     print(b + ': ' + arguments[1]);
>     a = 0;
>     b = 0;
>     print(a + ': ' + arguments[0]);
>     print(b + ': ' + arguments[1]);
> }
js> func(100, 200);
100: 100
200: 200
0: 0
0: 0
js>

js> function func(a, b) {
>     if(arguments.length != 2) {
>         throw new Error('must give 2 arguments');
>     }
> }
js> func(10);

js: "<stdin>", line 40: exception from uncaught JavaScript throw: Error: must give 2 arguments
at <stdin>:40 (func)
at <stdin>:39

js> func(10, 20);
js>

js> function numberGenerator(length, begin, step) {
>     begin = begin || 0;
>     step = step || 1;
>     var numbers = [begin];
>     length--;
>     for(var i = 0; i < length; i++) {
>         numbers.push(numbers[i] + step);
>     }
>     return numbers;
> }
js> numberGenerator(10);
0,1,2,3,4,5,6,7,8,9
js> numberGenerator(10, 5);
5,6,7,8,9,10,11,12,13,14
js> numberGenerator(10, 5, 2);
5,7,9,11,13,15,17,19,21,23
js>

js> function func(option) {
>     option = {
>         x : option.x || 10,
>         y : option.y || 20,
>         z : option.z || 30
>     };
>     print(option.x);
>     print(option.y);
>     print(option.z);
> }

js> func({ x : 100 });
100
20
30
js> func({ x : 100, y : 200 });
100
200
30
js> func({ x : 100, y : 200, z : 300 });
100
200
300
js>