Skip to content Skip to sidebar Skip to footer

Javascript Grocery List

I am trying to create a groceryList program. Right now, I'm just working on some basic functions. Adding an item to my grocery list, removing an item from grocery list, viewing the

Solution 1:

You are moving from being able to store your items as simple strings to needing to store some contextual data about your items as well, ie whether you've marked them or not. You can start storing your items as javascript objects with a name and a marked flag.

function add_item(item){
    groceryList.push({
        name: item, 
        marked: false
    });
}
function view_list(){
    for (var i = 0; i < groceryList.length; i++){
        if (groceryList.length == 0)
        return;
        else
        // let's display marked off items differently 
        if (groceryList[i].marked){
            console.log("X " + groceryList[i].name);
        } else {
            console.log("- " + groceryList[i].name);
        }

    }
}
function mark_item(item){
    for (var i = 0; i <= groceryList.length; i++){
        if (groceryList[i].name == item) {
            // when we mark an item, we just set its flag
            groceryList[i].marked = true;
        }
    }
}

Post a Comment for "Javascript Grocery List"