A good JavaScript to add/remove items from/to array?

前端 未结 4 1802
名媛妹妹
名媛妹妹 2021-02-06 10:30

folks! Today I created this script that has the following functionality:

  • add new items to array
  • list all items from the array
  • remove an item from
4条回答
  •  有刺的猬
    2021-02-06 11:17

    Here's some tips to, at least, make your code more portable (dunno if it will be better performance wise, but should be, since DOM Manipulation is less expensive)

    Tips

    1. First separate your event handle from the HTML
    2. Pass the "new food" as a function paramater
    3. Tie the array elements to the DOM using the ID
    4. Instead of rerendering everything when something changes (using innerHTML in the list), just change the relevant bit

    Benefits:

    1. You actually only loop once (when removing elements from the array).
    2. You don't re-render the list everytime something changes, just the element clicked
    3. Added bonus: It's more portable.
    4. Should be faster

    Example code:

    FIDDLE

    HTML

    JS

    // FoodList Class
    var FoodList = function (selectorID) {
        return {
            foodArray: [],
            listEl: document.getElementById(selectorID),
            idCnt: 0,
            add: function (newFood) {
                var id = 'myfood-' + this.idCnt;
                this.foodArray.push({
                    id: id,
                    food: newFood
                });
                var foodDom = document.createElement('div'),
                    foodText = document.createTextNode(newFood);
                foodDom.setAttribute('id', id);
                foodDom.setAttribute('class', 'aFood');
                foodDom.appendChild(foodText);
                this.listEl.appendChild(foodDom);
                ++this.idCnt;
            },
            remove: function (foodID) {
                for (var f in this.foodArray) {
                    if (this.foodArray[f].id === foodID) {
                        delete this.foodArray[f];
                        var delFood = document.getElementById(foodID);
                        this.listEl.removeChild(delFood);
                    }
                }
            }
        };
    };
    
    //Actual app
    window.myFoodList = new FoodList('foods');
    
    document.getElementById('eventBinder').addEventListener('click', function (e) {
        if (e.target.id === 'addFoodBtn') {
            var food = document.getElementById('addFood').value;
            window.myFoodList.add(food);
        } else if (e.target.className === 'aFood') {
            window.myFoodList.remove(e.target.id);
        }
    }, false);
    

提交回复
热议问题