跳轉到內容

JavaScript/實用提示

來自華夏公益教科書



預定義函式

[編輯 | 編輯原始碼]

在整個華夏公益教科書中,都提供了程式碼示例。通常,它們會在瀏覽器的某個地方顯示其結果。這是透過與Web API 介面對齊並實施在瀏覽器中的方法完成的。

函式 alert() 建立一個模式視窗,顯示給定的文字。

let x = 5;
window.alert("The value of 'x' is: " + x); // explicit notation
alert("The value of 'x' is: " + x);        // short notation

函式 log() 將訊息寫入瀏覽器的控制檯。控制檯是瀏覽器的視窗,通常不會開啟。在大多數瀏覽器中,您可以透過功能鍵 F12 開啟控制檯。

let x = 5;
console.log("The value of 'x' is: " + x); // explicit notation
                                          // no short notation

函式 print() 開啟列印對話方塊以列印當前文件。

window.print(); // explicit notation
print();        // short notation

函式 prompt() 開啟一個模式視窗並讀取使用者輸入。

let person = window.prompt("What's your name?"); // explicit notation
person = prompt("What's your name?");            // short notation
alert(person);

使用 document.write()強烈不推薦的。

編碼風格

[編輯 | 編輯原始碼]

我們的程式碼示例大多包含在任何其他語句之前的 "use strict"; 行。這建議編譯器執行額外的詞法檢查。他特別檢測使用在它們接收值之前未宣告的變數名。

"use strict";
let happyHour = true;
hapyHour = false; //  ReferenceError: assignment to undeclared variable hapyHour

如果沒有 "use strict"; 語句,編譯器將生成一個帶有拼寫錯誤的名稱的第二個變數,而不是生成錯誤訊息。

部分程式碼示例中的錯誤視覺化

[編輯 | 編輯原始碼]

由於華夏公益教科書模板 quiz 中的輕微錯誤,您將在某些示例中看到 } // 而不是 }。末尾的兩個斜槓只是為了克服這個問題而顯示的;它們不是必需的。

// the two slashes in the last line are not necessary
if (x == 5) {
  ...
} //
華夏公益教科書