我正在尝试创建一个杂货清单程序。现在我只是在做一些基本的功能。将商品添加到我的购物清单中、从购物清单中删除商品、查看购物清单以及标记我是否已拿起该商品。我困惑于如何让“标记”功能正常工作,这是我的代码:
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
在它的旁边。我想知道是否有人对我如何解决这个问题有建议?
您正在从能够将项目存储为简单的字符串转变为需要存储有关项目的一些上下文数据,即无论您是否已标记它们。您可以开始将项目存储为具有名称和标记标志的 javascript 对象。
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;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)