Last active
March 16, 2019 17:52
-
-
Save andy922200/f2fede0278d894eae8f2f516bf5b85ca to your computer and use it in GitHub Desktop.
[JS101] 用 JavaScript 一步步打造程式基礎 - 迴圈&函式
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment