DOM 操作:認為有用
以下部分問題需要您編寫一些DOM 操作程式碼來完成——例如,透過 JavaScript 建立新的 HTML 元素,將其文字內容設定為等於特定的字串值,並將它們巢狀在頁面上現有的元素內部。
我們尚未在課程中明確教授過這部分內容,但您應該會看到一些使用了它的示例,我們希望您能夠自行研究需要哪些 DOM API 來成功回答問題。一個好的起點是我們的DOM 指令碼入門教程。
迴圈 1
在我們的第一個迴圈任務中,我們希望您編寫一個基本的迴圈,該迴圈遍歷 `myArray` 中的所有項,並將它們顯示在螢幕上,作為列表項(<li> 元素)的內部。它們應該被追加到提供的 `list` 中。
js
const myArray = ["tomatoes", "chick peas", "onions", "rice", "black beans"];
const list = document.createElement("ul");
const section = document.querySelector("section");
section.appendChild(list);
// Don't edit the code above here!
// Add your code here
點選此處顯示解決方案
你完成的 JavaScript 應該看起來像這樣
js
// ...
// Don't edit the code above here!
for (let item of myArray) {
const listItem = document.createElement("li");
listItem.textContent = item;
list.appendChild(listItem);
}
迴圈 2
在接下來的任務中,我們希望您編寫一個簡單的程式,該程式接收一個姓名,在一個包含姓名和電話號碼的物件陣列中進行搜尋,如果找到該姓名,則將姓名和電話號碼輸出到一個段落中。
您將從以下三個變數開始
name:包含要搜尋的姓名。para:包含一個段落的引用,將用於報告結果。phonebook:包含要搜尋的電話簿條目。
注意:如果您尚未閱讀物件相關內容,請不用擔心!目前,您只需要知道如何訪問成員-值對即可。您可以在JavaScript 物件基礎教程中瞭解物件。
完成任務
- 編寫一個迴圈,遍歷(
phonebook)陣列並搜尋提供的name。您應該使用與上一個任務中不同的迴圈型別。 - 如果找到
name,則將其和相關的number寫入提供的段落(para)的textContent中,格式為“<姓名>的電話是 <號碼>。”之後,在迴圈完成之前退出迴圈。 - 如果沒有物件包含
name,則將“在電話簿中未找到姓名”列印到提供的段落(para)的textContent中。
js
const name = "Mustafa";
const para = document.createElement("p");
const phonebook = [
{ name: "Chris", number: "1549" },
{ name: "Li Kang", number: "9634" },
{ name: "Anne", number: "9065" },
{ name: "Francesca", number: "3001" },
{ name: "Mustafa", number: "6888" },
{ name: "Tina", number: "4312" },
{ name: "Bert", number: "7780" },
{ name: "Jada", number: "2282" },
];
const section = document.querySelector("section");
section.appendChild(para);
// Don't edit the code above here!
// Add your code here
點選此處顯示解決方案
你完成的 JavaScript 應該看起來像這樣
js
// ...
// Don't edit the code above here!
for (let i = 0; i < phonebook.length; i++) {
if (phonebook[i].name === name) {
para.textContent = `${phonebook[i].name}'s number is ${phonebook[i].number}.`;
break;
}
if (i === phonebook.length - 1) {
para.textContent = "Name not found in the phonebook";
}
}
迴圈 3
在最後一個任務中,您將測試從 500 到 2 的每個數字,使用提供的測試函式找出哪些是質數,並打印出這些質數。
您將獲得以下內容
i:初始值為500;用作迭代器。para:包含一個段落的引用,將用於報告結果。isPrime():一個函式,傳入一個數字,如果該數字是質數則返回true,否則返回false。
完成任務
- 編寫一個迴圈,遍歷從
500到2的每個數字(1 不被計為質數),並對每個數字執行提供的isPrime()函式。 - 對於不是質數的數字,繼續下一個迴圈迭代。對於是質數的數字,將其與某種分隔符一起新增到段落的
textContent中。
您應該使用與前兩個任務中不同的迴圈型別。
js
let i = 500;
const para = document.createElement("p");
const section = document.querySelector("section");
function isPrime(num) {
for (let i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
// Don't edit the code above here!
// Add your code here
// Don't edit the code below here!
section.appendChild(para);
點選此處顯示解決方案
你完成的 JavaScript 應該看起來像這樣
js
// ...
// Don't edit the code above here!
do {
if (isPrime(i)) {
para.textContent += `${i}, `;
}
i--;
} while (i > 1);
// Don't edit the code below here!
// ...