第二章 函式簡介
1 第一個函式示例
1 <script language="JavaScript" type="text/JavaScript"> 2 3 function bark(name,weight) 4 5 { 6 7 if(weight>20) 8 9 console.log(name+" says WOOF WOOF"); 10 11 else 12 13 console.log(name+" says woof woof"); 14 15 } 16 17 bark("rover",23); 18 19 bark("spot",18); 20 21 </script>
2 函式引數錯誤處理
傳入引數不夠,將沒有相應引數實參的形參設定成未定義
如果傳遞的引數太多,js將忽略多餘的引數
如果無return返回undefined
第三章 陣列
1 第一個示例
1 var score=[]; 2 3 var myarray=new Array(3); 4 5 myarray[1]="asdf"; 6 7 scores=[60,50,60,58,54,52]; 8 9 var solution2=scores[2]; 10 11 var Length=scores.length; 12 13 alert("There are "+Length+"solutions and Solution 2 produced "+solution2+" bubbles."+"and "+myarray[1]+"!");
2 第二個示例:
1 <!doctype html> 2 3 <html lang="en"> 4 5 <head> 6 7 <title>Battleship</title> 8 9 <meta charset="utf-8"> 10 11 </head> 12 13 <body> 14 15 <script language="JavaScript" type="text/JavaScript"> 16 17 var scores=[60,50,60,58,54,54, 18 19 58,50,52,54,48,69, 20 21 34,55,51,52,44,51, 22 23 69,64,66,55,52,61, 24 25 46,31,57,52,44,18, 26 27 41,53,55,61,51,44]; 28 29 var highscore=printAndGetHighScore(scores); 30 31 console.log("Bubbles test: "+scores.length); 32 33 console.log(" Hightest Bubble score: "+highscore); 34 35 var bestSolutions=[]; 36 37 bestSolutions=getBestResults(scores,highscore); 38 39 console.log("Solution with the hightest score: "+bestSolutions); 40 41 function printAndGetHighScore(scores) 42 43 { 44 45 var highscore=0; 46 47 var output; 48 49 for(var i=0;i<scores.length;i++) 50 51 { 52 53 output="Bubble solutoin #"+i+" score: "+scores[i]; 54 55 console.log(output); 56 57 if(scores[i]>highscore) 58 59 highscore=scores[i]; 60 61 } 62 63 return highscore; 64 65 } 66 67 function getBestResults(scores,highscore) 68 69 { 70 71 var bestSolutions=[]; 72 73 //var j=0; 74 75 for(var i=0;i<scores.length;i++) 76 77 { 78 79 if(scores[i]==highscore) 80 81 { 82 83 //bestSolutions[j]=i; 84 85 //j++; 86 87 bestSolutions.push(i); 88 89 } 90 91 } 92 93 return bestSolutions; 94 95 } 96 97 </script> 98 99 </body> 100 101 </html>