章節連結
為了讓自己更進入學習狀況,開始嘗試在 Lidemy 鋰學院 上的 JavaScript 課程。這篇文章主要內容為「迴圈」要如何使用。
重點概要和個人補充資料
可以開瀏覽器的 Devtool 來除錯:在指令中加入 debugger。
指令
do…while(條件),同時可善用 continue, break 來進入下一圈或中斷迴圈
while:先判斷條件,再執行
for loop:for (初始值;終止條件;值的變化){迴圈要做的事情}
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
/*debugger 除錯用& do/while */ | |
var i = 1 | |
debugger | |
do { | |
console.log(i++) | |
}while(i <= 100) | |
console.log("Finished!") | |
/*for loop 範例*/ | |
var scores = [10,20,30,40,50] | |
var sum = 0 | |
var avg = 0 | |
for (var i=0; i<scores.length; i++){ | |
console.log(scores[i]) | |
sum += scores[i] | |
} | |
avg = sum/scores.length | |
console.log('Total score is '+ sum +'.') | |
console.log('Average score is '+ avg+'.') | |
/*function 範例*/ | |
function array(min, max){ | |
var result = [] | |
for (var i = min; i<= max; i += 2){ | |
result.push(i) | |
} | |
return result | |
} | |
console.log(array(1,20)) | |
/*function 可以帶入 function*/ | |
function change(array, trans){ | |
var result = [] | |
for(var i = 0; i<array.length; i++){ | |
result.push(trans(array[i])) | |
} | |
return result | |
} | |
function linear(x){ | |
return x*2+1 | |
} | |
console.log( | |
change([1,2,3],linear) | |
) | |
/*印出橫向的星號*/ | |
function star(num){ | |
var result = '' | |
for (var i = 1; i <= num; i++){ | |
result += '*' | |
} | |
return result | |
} | |
console.log(star(5)) | |
/*.sort排序,數字由小到大*/ | |
var arr = [ 3, 25, 4, 67] | |
arr.sort(function(a,b){ | |
if (a===b) return 0 | |
if (b>a) return -1 /*負數不換位置*/ | |
return 1 /*正數換位置*/ | |
}) | |
console.log(arr) |