gpt4 book ai didi

JavaScript 杂货 list

转载 作者:行者123 更新时间:2023-11-28 15:23:21 25 4
gpt4 key购买 nike

我正在尝试创建一个杂货 list 程序。现在我只是在做一些基本的功能。将商品添加到我的购物 list 中、从购物 list 中删除商品、查看购物 list 以及标记我是否已拿起该商品。我困惑于如何让“标记”功能正常工作,这是我的代码:

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

关于JavaScript 杂货 list ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30295726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com