我正在用JavaScript构建一个自动售货机来学习它。但现在我有个问题。所有的值都来自我移交的3个输入字段。所以我想建立一个函数来检查零食是否已经存在。如果它存在,它应该添加新的价格和现有的股票将添加与我的输入字段的股票。如果零食不在机器中,它将被添加。这是我已经有的。
var selection = [
{name: "fanta", price: 1.60, stock: 4},
{name: "cola", price: 1.70, stock: 3},
{name: "nuts", price: 1.10, stock: 8},
{name: "mars", price: 1.20, stock: 2},
{name: "snickers", price: 1.20, stock: 5}
];
function new_snack_snack(selection){
var new_price_input = document.getElementById("new_price").value;
var new_stock_input = document.getElementById("new_stock").value;
var new_snack_input = document.getElementById("new_snack").value;
selection.push({name: new_snack_input, price: new_price_input, stock: new_stock_input});
console.log(selection);
document.getElementById("snack_table_output").innerHTML = create_table();
}
var selection = [{
name: "fanta",
price: 1.60,
stock: 4
},
{
name: "cola",
price: 1.70,
stock: 3
},
{
name: "nuts",
price: 1.10,
stock: 8
},
{
name: "mars",
price: 1.20,
stock: 2
},
{
name: "snickers",
price: 1.20,
stock: 5
}
];
function new_snack_snack(selection) {
var new_price_input = document.getElementById("new_price").value;
var new_stock_input = document.getElementById("new_stock").value;
var new_snack_input = document.getElementById("new_snack").value;
if (!selection.find(item => item.name === new_snack_input) {
selection.push({
name: new_snack_input,
price: new_price_input,
stock: new_stock_input
});
}
console.log(selection);
document.getElementById("snack_table_output").innerHTML = create_table();
}