-
-
Save kobitoDevelopment/98d9c15527920f05da7edc3a7a4e1201 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h2>Mapと仲良くなる</h2> | |
<button id="addItem">配列の最後に追加</button> | |
<button id="removeByIndex">インデックス1を削除</button> | |
<button id="removeById">最初のIDを削除</button> | |
<button id="updateById">最初の要素を更新</button> | |
<button id="clearItems">すべての要素をクリア</button> | |
<ul id="itemList"></ul> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const data = [ | |
{ id: 1, name: "Item 1" }, | |
{ id: 2, name: "Item 2" }, | |
{ id: 3, name: "Item 3" }, | |
]; | |
// アイテムリストを表示する関数 | |
const renderList = () => { | |
const itemList = document.getElementById("itemList"); | |
itemList.innerHTML = ""; // リストをクリア | |
data.forEach((item, index) => { | |
const li = document.createElement("li"); | |
li.textContent = `${index}: ${item.name} (ID: ${item.id})`; | |
itemList.appendChild(li); | |
}); | |
}; | |
// 配列の最後に新しい要素を追加 | |
const addItem = () => { | |
const newItem = { | |
id: Date.now(), | |
name: `Item ${data.length + 1}`, | |
}; | |
data.push(newItem); | |
renderList(); | |
}; | |
// 配列の特定のインデックスの要素を削除 | |
const removeByIndex = (index) => { | |
data.splice(index, 1); // 指定されたインデックスを削除 | |
renderList(); | |
}; | |
// 特定のIDの要素を削除 | |
const removeById = (id) => { | |
const index = data.findIndex((item) => item.id === id); | |
if (index !== -1) { | |
data.splice(index, 1); // 指定されたIDの要素を削除 | |
} | |
renderList(); | |
}; | |
// 特定のIDの要素を更新 | |
const updateById = (id, newName) => { | |
const index = data.findIndex((item) => item.id === id); | |
if (index !== -1) { | |
data[index].name = newName; // 指定されたIDのnameを更新 | |
} | |
renderList(); | |
}; | |
// すべての要素をクリア | |
const clearItems = () => { | |
while (data.length > 0) { | |
data.pop(); // 配列を空にする | |
} | |
renderList(); | |
}; | |
// イベントリスナーを追加 | |
document.getElementById("addItem").addEventListener("click", addItem); | |
document.getElementById("removeByIndex").addEventListener("click", () => removeByIndex(1)); | |
document.getElementById("removeById").addEventListener("click", () => removeById(data[0].id)); | |
document.getElementById("updateById").addEventListener("click", () => updateById(data[0].id, "Updated Item")); | |
document.getElementById("clearItems").addEventListener("click", clearItems); | |
// 初期リスト表示 | |
renderList(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment