JavaScript Grocery List

别来无恙 提交于 2021-02-05 09:43:00

问题


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 grocery list, and also marking if I have picked the item up. I am stuck on how I can get the 'marking' function to work properly, here is my code:

var groceryList = [];

function add_item(item){
    groceryList.push(item);
}

function remove_item(item){
    for (var i = 0; i <= groceryList.length; i++){
        if (groceryList[i] === item) groceryList.splice(i, 1);
    }
}

function view_list(){
    for (var i = 0; i < groceryList.length; i++){
        if (groceryList.length == 0)
        return;
        else
        console.log("- " + groceryList[i]);
    }
}

function mark_item(item){
    for (var i = 0; i <= groceryList.length; i++){
        if (groceryList[i] == item) console.log("X " + groceryList[i]);
    }
}

view_list();
add_item('banana');
add_item('apple');
view_list();
add_item('testies');
view_list();
remove_item('testies');
view_list();
mark_item('apple');

Obviously when I run the mark_item function it just prints the item I put in with an X next to it. I'm wondering if someone has suggestions on how I can approach this?


回答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;
        }
    }
}


来源:https://stackoverflow.com/questions/30295726/javascript-grocery-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!