close

function 函式 是為一個方法使用的方式:

function count(price,amount) {
var total = price * amount;
return total;
}
 
var money = count(50,5);
 
console.log(money);

function 函式名稱(帶入變數名稱1,帶入變數名稱1) {

內容

}

上列為基礎 函式使用方式

並且可以用來

直接從js程式碼直接呼叫這個函式()來做為使用

 

就上例而言 我的 函式名稱為 count 並帶入兩個參數(price, amount) 給這個函式做為使用

 

函式裡面宣告一個 total 的變數  將 price * amocunt 宣告給total 

 

最後並return --> total 出來 這個函式基本使用方式 就是將兩個 變數做相乘之後並將最後結果 return (返回)

 

最後我宣告一個 money = count(50,5);

 

count這個函式 將最後運算結果的 total 返回給我 結果為 250

 

也可以試著 使用 console.log(count(....));

 

將值帶進去,從網頁測試看看結果喔! 

---------------------------------------------------------------------------------------------------------------------

接下來介紹一下 全域變數與區域變數

 

 
var a = 10; //a為全域變數
var b = 5; //b為全域變數
count(a,b);
function count(price,amount) {
var total = price * amount;
console.log(total,"在函式內呼叫 --> 區域變數");
return total;
}
 
console.log(count(a,b));
console.log(a,b,"全域變數")
console.log(total,"外面呼叫-->區域變數");

最後結果為 

 

50 "在函式內呼叫 --> 區域變數"    ---> 此次為 count(a,b)呼叫了這個方法去執行 裡面的console.log(total) 帶出來 
50 "在函式內呼叫 --> 區域變數"    ---> console.log(count(a,b)); 首先執行了 在count(a,b) 裡面的console.log
50 --> console.log(count(a,b)); 直接將結果帶出來 return total
10 5 "全域變數"   --> 在這裡可以直接找到 全域變數的 a,b 因為我們有宣告在外面!!
Uncaught ReferenceError: total is not defined  --> console.log(total,"外面呼叫-->區域變數");
    at main.js:13

最後為什麼在函式 明明就有宣告total 但卻為什麼取不到東西呢?

這是因為function 在每次做完

都會清除裡面宣告的變數

所以在函式裡面的變數 可以命名成 在其它函式 曾宣告的變數 而不會影響到 原本函式的邏輯喔!!

arrow
arrow

    Haix 發表在 痞客邦 留言(0) 人氣()