# ➤ 什麼是 JavaScript ## 🔽 01. JavaScript 是什麼? <iframe height="300" style="width: 100%;" scrolling="no" title="01. JavaScript 是什麼?" src="https://codepen.io/yenying0804/embed/dyjGZLQ?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/dyjGZLQ"> 01. JavaScript 是什麼?</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## 🔽 02 . 如何在網頁中增加 JavaScript ? <iframe height="300" style="width: 100%;" scrolling="no" title="02 . 如何在網頁中增加 JavaScript ?" src="https://codepen.io/yenying0804/embed/qBybpyz?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/qBybpyz"> 02 . 如何在網頁中增加 JavaScript ?</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ### async 和 defer ==async== (能盡快被載入完畢=>立即被執行,就應該使用 async ) 使用 async 屬性(如下所示)所載入的腳本,在下載的同時不會讓網頁的渲染被阻塞(停住),並且在下載完成後馬上執行。它並不保證腳本會按照任何特定的順序執行,只保證不去妨礙網頁中其他部分顯示工作。async 的最佳使用情境,是當網頁中的腳本間彼此獨立,因而不依賴彼此運行的狀況下。 ```javascript= <script async src="js/vendor/jquery.js"></script> <script async src="js/script2.js"></script> <script async src="js/script3.js"></script> ``` ==defer== 所載入的腳本,會在腳本與內容都下載完成後,依照出現順序被執行。 ```javascript= <script defer src="js/vendor/jquery.js"></script> <script defer src="js/script2.js"></script> <script defer src="js/script3.js"></script> ``` ==註解== 單行註解 ``` // 我是一個註解 ``` 多行註解 ``` /* 我也是 一個註解 */ ``` ## 🔽 03.初次接觸Javascript <iframe height="300" style="width: 100%;" scrolling="no" title="03.初次接觸Javascript" src="https://codepen.io/yenying0804/embed/eYjJjZZ?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/eYjJjZZ"> 03.初次接觸Javascript</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## 🔽 04.出了什麼問題?JavaScript 疑難排解 <iframe height="300" style="width: 100%;" scrolling="no" title="04.出了什麼問題?JavaScript 疑難排解" src="https://codepen.io/yenying0804/embed/ZEjQVyr?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/ZEjQVyr"> 04.出了什麼問題?JavaScript 疑難排解</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ```javascript= 一個紅色的「X」代表這是一個錯誤訊息。 「TypeError: guessSubmit.addeventListener is not a function(TypeError: guessSubmit.addeventListener 並不是一個函式)」 ``` 首先,我們呼叫[Math.random()](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Math/random)以產生一個介於 0 到 1 的隨機小數,例如:0.5675493843 ==Math.random()== 接著,我們將Math.random()產生的隨機小數傳進[Math.floor()](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Math/floor),函式會回傳小於等於所給數字的最大整數,然後為這個整數值加 1: ==Math.floor(Math.random()) + 1== 由於Math.floor是無條件捨去取整數(地板值),所以一個介於 0 到 1 的隨機小數永遠只會得到 0,幫這個小數加 1 的話又會永遠只得到 1。所以進位前我們先幫隨機小數乘上 100,如此一來我們就能得到介於 0 到 99 的隨機數字了: ==Math.floor(Math.random()*100);== 別忘了還要加上 1,數字範圍才能成功介於 1 到 100: ==Math.floor(Math.random()*100) + 1;== ```javascript= 語法錯誤:語句缺少「 ; 」 SyntaxError: missing ; before statement 這個錯誤是指每行程式碼結束時必須加上英文輸入法的分號;(請注意不要打成中文輸入法),分號被遺忘的錯誤有時不太容易發現 ``` ```javascript= var userGuess = Number(guessField.value); 改成 var userGuess === Number(guessField.value); 此時程式碼會回報錯誤,因為瀏覽器會認為你想設定不同的東西;我們需要確保自己沒有誤用、混用指派運算子(=):用於賦予變數值跟嚴格比較運算子(===):用於比較兩個值是否完全相等,並回覆true/false布林值。 ``` ```javascript= 無論輸入什麼,程式總是顯示「你贏了」 還有另一種混用指派運算子(=)與嚴格比較運算子(===)的狀況,舉例如果我們將變數 checkGuess()中的嚴格比較運算子(===) if (userGuess === randomNumber) { 改成指派運算子(=) if (userGuess = randomNumber) { 這個檢查就失效了,程式會永遠回傳 true而勝利並結束遊戲。請小心! ``` ```javascript= 語法錯誤:參數列表後面缺少「)」 SyntaxError: missing ) after argument list 這個錯誤通常與 JavaScript 物件格式錯誤有關 function checkGuess() { 改成 function checkGuess( { 小心括號的部分!這會讓瀏覽器誤以為我們要把函式的程式內容當成函式參數傳入。 ``` ```javascript= 語法錯誤:函式結尾缺少「}」大括號 SyntaxError: missing } after function body 很簡單——這通常意味你的函式或條件結構式缺少一個大括號。若我們將checkGuess()函式末段的一個結尾大括號刪除,就會獲得這個錯誤。 ``` ```javascript= 語法錯誤:預期得到表達式,但實際得到「字串」 SyntaxError: expected expression, got 'string' 或是 語法錯誤:字串字面值未正常結束 SyntaxError: unterminated string literal 這些錯誤通常意味著你漏寫一個字串起始或結尾的引號,上面第一個錯誤表示漏寫了字串開頭的起始引號,這導致這裡的「string」會替換瀏覽器發現的意外字串。第二個錯誤則表示字串結尾缺少了結束引號。 ``` [JavaScript 錯誤參考資料](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Errors) ## 🔽 05.存儲您需要的資訊 - 變數 <iframe height="300" style="width: 100%;" scrolling="no" title="05.存儲您需要的資訊 - 變數" src="https://codepen.io/yenying0804/embed/wvxMVva?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/wvxMVva"> 05.存儲您需要的資訊 - 變數</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ```= 良好的命名範例: age myAge init initialColor finalOutputValue audio1 audio2 ``` ```javascript= Numbers 數字 let myAge = 17; Strings 字串 let dolphinGoodbye = 'So long and thanks for all the fish'; Booleans 布林值 let iAmAlive = true; let test = 6 < 3; Arrays 陣列 let myNameArray = ['Chris', 'Bob', 'Jim']; let myNumberArray = [10, 15, 40]; myNameArray[0]; // should return 'Chris' myNumberArray[2]; // should return 40 Objects 物件 let dog = { name : 'Spot', breed : 'Dalmatian' }; //取得物件中儲存的資料 dog.name 動態型別 let myString = 'Hello'; let myNumber = '500'; // 糟糕,這仍然是一個字符串 typeof myNumber; myNumber = 500; // 現在這是個數字 typeof myNumber; ``` ## 🔽 let 、 const <iframe height="300" style="width: 100%;" scrolling="no" title="let 、 const" src="https://codepen.io/yenying0804/embed/KKBVgvy?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/KKBVgvy"> let 、 const</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ### let ==let 並不會在全域物件中建立變數。== ```javascript= function varTest() { var x = 1; { var x = 2; // 這裡的 x 與 function 區塊內部的 x 是一樣的,因此會影響 function 區塊內所有的 x console.log(x); // 2 } console.log(x); // 2 } function letTest() { let x = 1; { let x = 2; // 這裡的 x 與 function 區塊內部的 x 是不同的,只會作用在這層 block 區塊中 console.log(x); // 2 } console.log(x); // 1 } ``` ### const ==JavaScript 中的常數,一經宣告就不改變的值。== ```javascript= const daysInWeek = 7; const hoursInDay = 24; const daysInWeek = 7; daysInWeek = 8; ``` ## 🔽 06.JavaScript中的基本數學 - 數字和運算符 <iframe height="300" style="width: 100%;" scrolling="no" title="06.JavaScript中的基本數學 - 數字和運算符" src="https://codepen.io/yenying0804/embed/Yzjwmoy?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/Yzjwmoy"> 06.JavaScript中的基本數學 - 數字和運算符</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ```javascript= 遞增和遞減運算符 let num1 = 4; num1++; console.log(num1); ``` [運算式與運算子](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators) ```javascript= 在 JavaScript 中,你可以選擇用單引號或雙引號來包住字串。 let sgl = 'Single quotes.'; let dbl = "Double quotes"; sgl; dbl; let sglDbl = 'Would you eat a "fish supper"?'; let dblSgl = "I'm feeling blue."; sglDbl; dblSgl; ``` ```javascript= 字串中的跳脫字元 let bigmouth = 'I\'ve got no right to take my place...'; bigmouth; ``` [跳脫符號](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/String#escape_notation) ## 🔽 07.處理文字 - JavaScript中的字串 <iframe height="300" style="width: 100%;" scrolling="no" title="07.處理文字 - JavaScript中的字串" src="https://codepen.io/yenying0804/embed/bGjpGbQ?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/bGjpGbQ"> 07.處理文字 - JavaScript中的字串</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## [樣板字面值](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Template_literals) ```javascript= `string text` `string text line 1 string text line 2` `string text ${expression} string text` tag `string text ${expression} string text` ``` ```javascript= let song = 'Fight the Youth'; // 模版字符串 song = `Fight the Youth`; let score = 9; let highestScore = 10; let output = 'I like the song "' + song + '". I gave it a score of ' + (score/highestScore * 100) + '%.'; // 模版字符串 output = `I like the song "${ song }". I gave it a score of ${ score/highestScore * 100 }%.`; ``` ```javascript= //模版字符串 let examScore = 45; let examHighestScore = 70; examReport = `You scored ${ examScore }/${ examHighestScore } (${ Math.round((examScore/examHighestScore*100)) }%). ${ examScore >= 49 ? 'Well done, you passed!' : 'Bad luck, you didn\'t pass this time.' }`; ``` ```javascript= 運算式內插 var a = 5; var b = 10; console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.'); // "Fifteen is 15 and // not 20." var a = 5; var b = 10; console.log(`Fifteen is ${a + b} and not ${2 * a + b}.`); // "Fifteen is 15 and // not 20." ``` ```javascript= 巢狀樣板 var classes = 'header' classes += (isLargeScreen() ? '' : item.isCollapsed ? ' icon-expander' : ' icon-collapser'); const classes = `header ${ isLargeScreen() ? '' : (item.isCollapsed ? 'icon-expander' : 'icon-collapser') }`; const classes = `header ${ isLargeScreen() ? '' : `icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`; ``` ## 測試你的技能:字符串 ## 🔽 測試你的技能:字符串 01 <iframe height="300" style="width: 100%;" scrolling="no" title="測試你的技能:字符串 01" src="https://codepen.io/yenying0804/embed/LYBNpMm?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/LYBNpMm"> 測試你的技能:字符串 01</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## 🔽 測試你的技能:字符串 02 <iframe height="300" style="width: 100%;" scrolling="no" title="測試你的技能:字符串 02" src="https://codepen.io/yenying0804/embed/XWBdNMQ?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/XWBdNMQ"> 測試你的技能:字符串 02</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## 🔽 測試你的技能:字符串 03 <iframe height="300" style="width: 100%;" scrolling="no" title="測試你的技能:字符串 03" src="https://codepen.io/yenying0804/embed/PoBzygK?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/PoBzygK"> 測試你的技能:字符串 03</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## 🔽 測試你的技能:字符串 04 <iframe height="300" style="width: 100%;" scrolling="no" title="測試你的技能:字符串 04" src="https://codepen.io/yenying0804/embed/zYLBMqY?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/zYLBMqY"> 測試你的技能:字符串 04</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> --- ## 🔽 08. 有用的字符串方法01 <iframe height="300" style="width: 100%;" scrolling="no" title="08. 有用的字符串方法01" src="https://codepen.io/yenying0804/embed/KKBgNER?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/KKBgNER"> 08. 有用的字符串方法01</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## 🔽 08. 有用的字符串方法02 <iframe height="300" style="width: 100%;" scrolling="no" title="08. 有用的字符串方法02" src="https://codepen.io/yenying0804/embed/qByaROd?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/qByaROd"> 08. 有用的字符串方法02</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> --- ## 🔽 09. Arrays(陣列) <iframe height="300" style="width: 100%;" scrolling="no" title="09. Arrays(陣列)" src="https://codepen.io/yenying0804/embed/gOjLrGp?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/gOjLrGp"> 09. Arrays(陣列)</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## 🔽 主動學習:打印那些產品 <iframe height="300" style="width: 100%;" scrolling="no" title="Active learning: Printing those products" src="https://codepen.io/yenying0804/embed/MWBqxQe?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/MWBqxQe"> Active learning: Printing those products</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## 🔽 主動學習:前 5 個搜索 <iframe height="300" style="width: 100%;" scrolling="no" title="Active learning: Top 5 searches" src="https://codepen.io/yenying0804/embed/dyjgPBP?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/yenying0804/pen/dyjgPBP"> Active learning: Top 5 searches</a> by YenYing (<a href="https://codepen.io/yenying0804">@yenying0804</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> --- # ➤ 在代碼中做出決定 - 條件 條件敘述句(Conditional statements)讓我們能將這些決定的過程在 Javascript 表示出來,從一定得做出的選擇(例如:「吃一個或兩個餅乾」),到這些選擇的結果(或許「吃一個餅乾」會出現「還是會餓」這種結果,而「吃兩個餅乾」的結果會是「吃飽了,但因為吃了全部餅乾而被媽媽罵」)。  ## if ... else 敘述句 [if...else](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements/if...else) 基本的 if ... else 語法 ```javascript= if (condition) { code to run if condition is true } else { run some other code instead } ``` 1. 關鍵字 if 和後頭的括號。 2. 想測試的條件放在括號中(通常像是「這個值是否大於其他值」或是「這個值是否存在」等等)。這裡的條件會使用先前提過的 比較運算子(comparison operators),並且最後會回傳 true 或是 false。 3. 第一組大括號,在大括號裡面有一些程式碼 — 內容可以是任何我們所需要執行的程式碼,並且只有在條件句回傳 true 才會執行。 4. 關鍵字 else。 5. 另一組大括號,在大括號中我們一樣是放置所需的程式碼,並只有在條件句回傳 false 才會執行。 ==> 「如果條件回傳 true ,則執行程式 A,否則執行程式 B」。 else 和第二組大括號並不是必要的。 ```javascript= 此範例也能夠執行 if (condition) { code to run if condition is true } run some other code 在這個例子中的第二個區塊並沒有被條件式控制,也就是說無論條件式回傳的是 true 或是 false,它都會執行。 ``` 你可能有時候會看到 if...else 敘述是不加大括弧的: ```javascript= if (condition) code to run if condition is true else run some other code instead ``` 這當然也是有效的程式碼,但不太建議這樣用。使用大括弧能夠很清楚地看到程式區塊、縮排,也能夠擁有多行程式碼,對於程式的可讀性會提高許多。 --- 為了更好地理解這種語法,讓我們考慮一個真實的例子。 想像一下,一個孩子被他們的母親或父親請求幫助做家務。 父母可能會說:“嘿,親愛的,如果你幫我去購物,我會給你一些額外的津貼,這樣你就可以買得起你想要的玩具了。” 在 JavaScript 中,我們可以這樣表示: ```javascript= var shoppingDone = false; if (shoppingDone === true) { var childsAllowance = 10; } else { var childsAllowance = 5; } ```
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.