DAY 7
0

## 引數 (argument) 與 函式參數 (parameter)

• 引數是當我們呼叫函式時傳遞給它的值
• 參數是我們在函式定義中所列出的變數

## 宣告式 (declaration) 與 表達式 (expression)

``````function funA(){
...
}
``````

``````var myFun = function(){
...
}
``````

## 隱含引數

### arguments

``````function show(a,b,c){
console.log(a,b,c);
console.log(arguments);
console.log(arguments[0]);
console.log(arguments.length);
console.log(typeof arguments);
}
show(1,2,3);
``````

``````function show(a,b,c){
arguments.sort(function(a,b){
return a - b;
});
}
show(1,2,3);//Uncaught TypeError: arguments.sort is not a function
``````

``````function modifyArg(a,b,c){
console.log(a,b,c);//1 2 3
arguments[0] *= 20;
console.log(a,b,c);//20 2 3
}
modifyArg(1,2,3);
``````

``````function dynamicArg(){
console.log(arguments);
}
dynamicArg(1,2,3);//Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
``````

``````function mutli(){
let argLength = arguments.length;
if(argLength ===1){
console.log(argLength[0])
}else if(argLength ===2){
console.log(argLength[0],argLength[1])
}
...
}
``````

``````var people = {
name:["Dean Edwards", "Alex Russell", "Dean Tom","Alex Tsai","Tom Cruise","Tom Ford"]
}
``````

`find()` 時回傳所有人;
`find('Tom Cruise')` 時回傳 `["Tom Cruise"]`

``````var people = {
name:["Dean Edwards", "Alex Russell", "Dean Tom","Alex Tsai","Tom Cruise","Tom Ford"]
}

function addMethod (obj, key, fn) {
var old = obj[key];
obj[key] = function () {
if (fn.length === arguments.length) {
return fn.apply(this,arguments);
} else if (typeof old === "function") {
return old.apply(arguments);
}
}
}
``````

``````//沒有參數傳入，回傳所有人
function findAll () {
return people.name;
}

// 傳入一個參數時，回傳firstName相同的人名陣列
function findFirstName (firstName) {
var ret = [];
for (var i = 0; i < people.name.length; i++) {
if (people.name[i].indexOf(firstName) !== -1) {
ret.push(people.name[i]);
}
}
return ret;
}

// 傳入兩個參數時，回傳firstName和lastName都相同的人名陣列
function findFullName (firstName, lastName) {
var ret = [];
for (var i = 0; i < people.name.length; i++) {
if (people.name[i] === (firstName + " " + lastName)) {
ret.push(people.name[i]);
}
}
return ret;
}
``````

``````addMethod(people, "find", findAll);

``````

``````console.log(people.find()); //["Dean Edwards", "Alex Russell", "Dean Tom", "Alex Tsai", "Tom Cruise", "Tom Ford"]
console.log(people.find("Tom")); //["Tom Cruise", "Tom Ford"]
console.log(people.find("Dean Edwards")); //["Dean Edwards"]
``````

``````function addMethod (obj, key, fn) {
var old = obj[key];
obj[key] = function () {
if (fn.length === arguments.length) {
return fn.apply(this,arguments);
} else if (typeof old === "function") {
return old.apply(arguments);
}
}
}
``````

``````if (fn.length === arguments.length) {
return fn.apply(this,arguments);
}
else if (typeof old === "function") {
return old.apply(this,arguments);
}
``````

``````else if (typeof old === "function") {
return old(arguments);
}
``````

`findFirstName` 由於傳入參數長度跟 `findFirstName` 長度相等，便會直接執行，不會在往上找。