᳓相關文章
᳓重點整理
- 利用typeof可以檢查傳入的參數是否為function。
- Callback function可以針對特定function的執行方式進行客製化,以sort()進行簡單的舉例,日後再詳細介紹各種可客製化的function及規則。
- Callback function可以回傳非同步呼叫(Asynchronous function)的執行結果,以setTimeout()進行簡單的舉例,日後再詳細介紹非同步呼叫與同步呼叫。
- 這篇文章開始換了一個新的工具:Visual Studio Code。能夠安裝JavaScript Standard Style的擴充功能,幫助維持程式碼格式一致,且不需要另外開啟小黑窗執行程式。細節及其他內容請參考陳鍾誠的文章"用JavaScript實踐⟪軟體工程⟫的那些事兒"。
᳓實作
typeof的寫法:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | |
* Check callback function using typeof | |
* 功能:利用typeof檢查傳入callback function的是否為function | |
* | |
*/ | |
let add = function(num1, num2){ | |
return num1 + num2; | |
} | |
let calc = function(num1, num2, callback){ | |
if(typeof callback === "function"){ | |
return callback(num1, num2); | |
} | |
else{ | |
return "error"; | |
} | |
} | |
console.log("2 + 3 = " + calc(2, 3, add)); | |
console.log("2 + 3 = " + calc(2, 3, 6)); |
執行結果 |
客製化的寫法(sort()):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | |
* Sort numbers in an array | |
* 功能:將Array中的數字進行三種排序 | |
* | |
*/ | |
let numbers = [1, 12, 8, 5, 6]; | |
console.log("原陣列:" + numbers); | |
console.log("預設排序:" + numbers.sort()); // 預設會將陣列值以字串的方式進行排序,因此排序結果為[1,12,5,6,8] | |
console.log("由小到大(ascending)排序:" + numbers.sort(function(a, b){return a - b})); // 排序結果為[1,5,6,8,12] | |
console.log("由大到小(descending)排序:" + numbers.sort(function(a, b){return b - a})); // 排序結果為[12,8,6,5,1] |
執行結果 |
回傳非同步呼叫執行結果的寫法(setTimeout()):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | |
* Display an console log after 3 seconds (3000 milliseconds) | |
* 功能:進入setTimeout三秒後再顯示一行字 | |
* | |
*/ | |
setTimeout(function(){ console.log("wait after 3 seconds!"); }, 3000); // 等待三秒後輸出 | |
console.log("Hi!"); // 由於setTimeout是非同步函數,因此執行的同時便接著執行這行,導致這行先輸出 |
執行結果 |
᳓其他參考文章
Techsith的Youtube影片"javascript callback functions tutorial"
W3Schools的文章"JavaScript Array sort() Method"
W3Schools的文章"Window setTimeout() Method"
Techsith的Youtube影片"javascript callback functions tutorial"
W3Schools的文章"JavaScript Array sort() Method"
W3Schools的文章"Window setTimeout() Method"
沒有留言:
張貼留言