跳轉到內容

JavaScript/控制結構/練習

來自華夏公益教科書,開放的書籍,開放的世界

主題:條件分支



1. 編寫一個指令碼,允許使用者輸入姓名(提示)。指令碼將根據姓名的長度做出相應的回答。

  • 最多 5 個字元:"您好,<name>。您的名字很短。"
  • 最多 10 個字元:"您好,<name>。您的名字長度適中。"
  • 超過 10 個字元:"您好,<name>。您的名字很長。"
點選檢視解決方案
"use strict";

const name = prompt("Please type your name: ");
const len = name.length;

if (len <= 5) {
  alert("Hello " + name + ". Your have a short name.");
} else if (len <= 10) {
  alert("Hello " + name + ". You have a name with a medium length.");
} else {
  alert("Hello " + name + ". Your name is very long.");
}



2. 編寫一個指令碼,允許使用者輸入單個字元。指令碼將判斷它是否為母音('a','e','i','o','u')或子音。

  • "您輸入了母音:<使用者輸入>"
  • "您輸入了子音:<使用者輸入>"
  • "您輸入了一個數字或其他字元(+, -, *, ...):<使用者輸入>"
點選檢視解決方案
"use strict";

const char = prompt("Please type a character: ");
const char2 = char.substring(0, 1).toUpperCase();

switch (char2) {
  case 'A':
  case 'E':
  case 'I':
  case 'O':
  case 'U':
    alert("You typed in the vocal: " + char);
    break;

  case 'B':
  case 'C':
  case 'D':
  // ... all the other consonants
    alert("You typed in the consonant: " + char);
    break;

  default:
    alert("You typed in a digit or some other character: (+, -, *, ...): " + char);
    break;
}



3. try / catch

  • 編寫一個指令碼,呼叫一個函式connectToDatabase()。此函式在您的指令碼中不存在,這會導致 JavaScript 引擎生成執行時錯誤。
  • 捕獲錯誤併產生有意義的錯誤。
  • 終止指令碼。
點選檢視解決方案
"use strict";

try {
  connectToDatabase();
  // ... SQL commands ...
} catch (err) {
  alert("The function 'connectToDatabase()' is not known. System error?");
  alert("The system error is: " + err);
} finally {
  // ... show 'good by' screen
  alert("Program terminates.");
}



1 結果是什麼?

"use strict";

const x = 0;
let y = 0;

if (x < 10) 
  alert("One");
  y = 20;

if (y === 0)
  alert("Two");

一條訊息
兩條訊息

2 'alert' 語句顯示什麼?

"use strict";
let x = 2;
switch (x) {
case 1:
  x++;
case 2:
  x++;
  x++;
case 3:
  x++;
  x++;
  x++;
default:
  x = 0;
} //
alert(x);

0
2
4
以上都不對

華夏公益教科書