JavaScript杂货清单 [英] JavaScript Grocery List

查看:83
本文介绍了JavaScript杂货清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个杂货店清单程序.现在,我只是在处理一些基本功能.将商品添加到我的购物清单中,从购物清单中删除一个商品,查看购物清单,并标记我是否已拾起该商品.我一直在坚持如何使标记"功能正常工作,这是我的代码:

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');

很显然,当我运行 mark_item 函数时,它只会打印我放入的项目,并在其旁边带有 X .我想知道是否有人对如何解决这个问题有建议?

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?

推荐答案

您正从能够将项目存储为简单字符串的方式转变为还需要存储有关项目的一些上下文数据,即是否标记了它们或不.您可以开始将项目存储为带有名称和标记标志的javascript对象.

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

这篇关于JavaScript杂货清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆