我正在尝试为食品配送网站编写订单(以了解有关Javascript中对象的更多信息),以便每个项目在选中时填充数组。如果项目被单击两次,它也应该识别请求的数量,而不是创建副本。这是我的代码,它有效,但似乎过长了。特别是,为了增加数量,我的最终循环似乎应该是多余的。这样做有更聪明的方法吗?
我从中绘制的JSON数据如下所示:
"dishes": [
{
"id": "1",
"name": "Jumbo Chicken Wings",
"description": "Honey, Ginger, Chilli, Soy",
"price": "4.50"
},
{
"id": "2",
"name": "Spiced Whitebait",
"description": "Lemon Mayonaise",
"price": "5"
}
这是我的(可能是超长)代码:
// ORDER FORM
// begin with empty array
var orderform = [];
function chooseDish() {
// when clicking on item...
$("#menu li").click(function(){
//create new object from item listed properties
var item = {
id: $(this).attr('id'),
dish: $(this).find("span.dish-name").text(),
price: $(this).find("span.dish-price").text()
};
// either add first item to array...
if (!orderform.length) {
item.quantity = 1;
orderform.push(item);
}
// or see if an object is already in the array.
else {
var hasDishBeenSelected = false;
for (var i = 0; i < orderform.length; i++) {
if (orderform[i].id === item.id) {
hasDishBeenSelected = true;
}
}
// if the item hasn't already been selected add the item...
if (!hasDishBeenSelected) {
item.quantity = 1;
orderform.push(item);
}
// otherwise increase that item's quantity by 1
else {
for (var j = 0; j < orderform.length; j++) {
if (orderform[j].id === item.id) {
orderform[j].quantity += 1;
}
}
}
}
console.table(orderform);
});
}
感谢您的任何提示!