JavaScript/原始資料型別/練習
外觀
< JavaScript | 原始資料型別
主題:原始資料型別
1. 編寫一個包含以下步驟的指令碼('power'-運算子為 '**')
- 計算 250 的值。將其儲存在變數
x1中。 - 計算 250 + 1 的值。將其儲存在變數
x2中。 - 比較
x1和x2。它們相等嗎?
點選檢視解決方案
"use strict";
const x1 = 2 ** 50;
const x2 = 2 ** 50 + 1;
alert(x1 == x2); // false
2. 使用 260 而不是 250 重複之前的練習。
點選檢視解決方案
"use strict";
const x1 = 2 ** 60;
const x2 = 2 ** 60 + 1;
alert(x1 == x2); // true
3. 使用 1000 而不是 1 重複之前的練習。
點選檢視解決方案
"use strict";
const x1 = 2 ** 60;
const x2 = 2 ** 60 + 1000;
alert(x1 == x2); // false
4. 與你的同事討論練習 1-3 的結果。
5. 編寫一個包含以下步驟的指令碼
- 計算三分之一的值。將結果儲存在變數
x1中。 - 顯示
x1。 - 將
x1乘以 3 並將結果儲存在x2中。 - 顯示
x2。你期望哪個值?
點選檢視解決方案
"use strict";
const x1 = 1 / 3;
alert(x1);
const x2 = x1 * 3;
alert(x2);
6. 編寫一個指令碼,它表明 5 和 5.0 是相同的值。
點選檢視解決方案
"use strict";
const x1 = 5;
const x2 = 5.0;
alert(x1 == x2);
7. 編寫一個指令碼,它
- 詢問使用者他的年齡:
prompt(...) prompt()總是返回一個字串。為了執行計算,有必要將答案轉換為數字parseInt()、parseFloat()、Number()- 如果他的答案是數值,則顯示他的心臟自出生以來的跳動次數(大約每秒一次)
- 否則,顯示一條訊息,例如“抱歉。我們需要數值才能執行計算”。
點選檢視解決方案
// a possible solution:
"use strict";
const answer = prompt("How old are you?"); // returns a string
const age = parseFloat(answer); // what's about parseInt() or Number() ?
if (Number.isNaN(age)) { // try other solutions!
alert("Sorry, we need a number to perform the calculation. You typed: '" + answer + "'");
} else {
// about one beat per second
const seconds = age * 365 * 24 * 60 * 60;
alert("Your heart has beaten (approximately) " + seconds + " times since your birth.");
}
8. 為之前的練習建立一個 HTML 頁面並將解決方案嵌入到 HTML 中。你可以參考 這個示例。
點選檢視解決方案
<!DOCTYPE html>
<html>
<head>
<title>Seconds</title>
<script>
function go() {
"use strict";
let result;
const answer = document.getElementById("age").value;
const age = Number(answer);
if (Number.isNaN(age)) { // try other solutions!
result = "Sorry, we need a number to perform the calculation. You typed: '" + answer + "'";
} else {
// about one beat per second
const seconds = age * 365 * 24 * 60 * 60;
result = "Your heart has beaten (approximately) " + seconds + " times since your birth.";
}
document.getElementById("result").innerText = result;
}
</script>
</head>
<body>
<h1>How many times has your heart beaten?</h1>
<label>Your age: </label>
<input type="text" id="age">
<button type="button" onclick="go()">GO</button>
<p>
<div id="result">???</div>
</p>
</body>
</html>