皆さん!今日、次の機能を持つこのスクリプトを作成しました。
- 配列に新しいアイテムを追加する
- 配列のすべての項目を一覧表示する
- 配列からアイテムを削除する
次の 2 つの機能があります。
- addToFood() - 入力の値を配列に追加し、div の innerHTML を更新します
- removeRecord(i) - 配列からレコードを削除し、div の innerHTML を更新します
コードには 3 つの for ループが含まれており、 http://jsfiddle.net/menian/3b4qp/1/で確認できます。
私のマスターは、これらの 3 つの for ループがソリューションを重いものにすると言っていました。同じことを行うより良い方法はありますか?ループを減らしてスプライスを使用する方が良いでしょうか? 前もって感謝します。
HTML
<!-- we add to our foodList from the value of the following input -->
<input type="text" value="food" id="addFood" />
<!-- we call addToFood(); through the following button -->
<input type="submit" value="Add more to food" onClick="addToFood();">
<!-- The list of food is displayed in the following div -->
<div id="foods"></div>
JavaScript
var foodList = [];
function addToFood () {
var addFood = document.getElementById('addFood').value;
foodList.push(addFood);
for (i = 0; i < foodList.length; i++) {
var newFood = "<a href='#' onClick='removeRecord(" + i + ");'>X</a> " + foodList[i] + " <br>";
};
document.getElementById('foods').innerHTML += newFood;
}
function removeRecord (i) {
// define variable j with equal to the number we got from removeRecord
var j = i;
// define and create a new temporary array
var tempList = [];
// empty newFood
// at the end of the function we "refill" it with the new content
var newFood = "";
for (var i = 0; i < foodList.length; i++) {
if(i != j) {
// we add all records except the one == to j to the new array
// the record eual to j is the one we've clicked on X to remove
tempList.push(foodList[i]);
}
};
// make redefine foodList by making it equal to the tempList array
// it should be smaller with one record
foodList = tempList;
// re-display the records from foodList the same way we did it in addToFood()
for (var i = 0; i < foodList.length; i++) {
newFood += "<a href='#' onClick='removeRecord(" + i + ");'>X</a> " + foodList[i] + " <br>";
};
document.getElementById('foods').innerHTML = newFood;
}