(Javascript)如何将重复的条目(项目,数量,价格)添加到现有数量中?

时间:2019-04-18 10:31:23

标签: javascript

我正在尝试制作一个简单的购物清单应用程序,其中列出了您要购买的商品,要购买的数量以及您要为之支付的预期价格(目前已手动输入)。然后,它将所有条目组织在一个表中。

我遇到的问题是要添加重复项。我希望将列表中原本重复的项目改为合并到现有项目中,并更新数量。

因此,如果提交了“ Cereal,10,4.99”,并且已经存在“ Cereal,15,5.99”,则代替创建新条目,将现有条目更新为

“谷物,25,5.99”(稍后我将弄清楚如何平均价格。)

这是我的最佳尝试,但不起作用:

USER_AUTHENTICATION_MQCSP

我的工作HTML:

for (var i=0; i<itemArray.length; i++) {
    if (itemArray[i] === newItemEntry) {
      quantityArray[i] = quantityArray[i] + newQuantityEntry;
    } else {
        itemArray.push(newItemEntry);
        quantityArray.push(newQuantityEntry);
        expectedPriceForEachArray.push(newExpectedPriceForEachEntry);
    }
}; 

我正在使用的Javascript:

<!DOCTYPE html>
<html lang="en">
<script src="script.js"></script>

<body>
    <h1>
        Enter an item, quantity, and the price you're expecting to pay.
    </h1>
    Item:<br>
    <br>
    <input type="text" placeholder="ketchup" id="itemForm">
    <br>
    <br> Quantity:
    <br>
    <br>
    <input type="number" placeholder="25" id="quantityForm">
    <br>
    <br> Expected Price for Each:<br>
    <br>
    <input type="number" placeholder="2.99" id="expectedPriceForEachForm">
    <br>
    <br>

    <button onclick="addToListOfEntries()">Add this entry to the list</button>
    <br>
    <br>
    <table id="myEntries" border='1' width='400'>
        <tr>
            <th>Item</th>
            <th>Quantity</th>
            <th>Expected Price For Each</th>
        </tr>
    </table>
</body>

</html>

var itemArray = []
var quantityArray = []
var expectedPriceForEachArray = []

function addToListOfEntries () {
  var table = document.getElementById("myEntries");
  var row = table.insertRow();
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);
  var newItemEntry = document.getElementById("itemForm").value
  var newQuantityEntry = document.getElementById("quantityForm").value
  var newExpectedPriceforEachEntry = document.getElementById("expectedPriceForEachForm").value

  itemArray.push(newItemEntry);
  quantityArray.push(newQuantityEntry);
  expectedPriceForEachArray.push(newExpectedPriceforEachEntry);

  for(var i=0; i<itemArray.length;i++)
  {
    cell1.innerHTML = itemArray[i];
    cell2.setAttribute('style', 'text-align: right;');
    cell2.innerHTML = quantityArray[i];
    cell3.setAttribute('style', 'text-align: right;');
    cell3.innerHTML = expectedPriceForEachArray[i] + " USD";
  }
}
var itemArray = []
var quantityArray = []
var expectedPriceForEachArray = []

function addToListOfEntries () {
  var table = document.getElementById("myEntries");
  var row = table.insertRow();
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);
  var newItemEntry = document.getElementById("itemForm").value
  var newQuantityEntry = document.getElementById("quantityForm").value
  var newExpectedPriceforEachEntry = document.getElementById("expectedPriceForEachForm").value

  itemArray.push(newItemEntry);
  quantityArray.push(newQuantityEntry);
  expectedPriceForEachArray.push(newExpectedPriceforEachEntry);

  for(var i=0; i<itemArray.length;i++)
  {
    cell1.innerHTML = itemArray[i];
    cell2.setAttribute('style', 'text-align: right;');
    cell2.innerHTML = quantityArray[i];
    cell3.setAttribute('style', 'text-align: right;');
    cell3.innerHTML = expectedPriceForEachArray[i] + " USD";
  }
}

3 个答案:

答案 0 :(得分:0)

请检查以下代码。

<!DOCTYPE html>
<html lang="en">
<script type="text/javascript">
var itemArray = []
var quantityArray = []
var expectedPriceForEachArray = []

function addToListOfEntries () {
  var table = document.getElementById("myEntries");
  while(table.rows.length > 1) {
    table.deleteRow(1);
  }
  var newItemEntry = document.getElementById("itemForm").value
  var newQuantityEntry = document.getElementById("quantityForm").value
  var newExpectedPriceforEachEntry = document.getElementById("expectedPriceForEachForm").value

  var index = itemArray.indexOf(newItemEntry);

  if( index > -1 ) {
      quantityArray[index] = Number(quantityArray[index]) + Number(newQuantityEntry);
      expectedPriceForEachArray[index] = Number(expectedPriceForEachArray[index]) + Number(newExpectedPriceforEachEntry);
  }else{
        itemArray.push(newItemEntry);
        quantityArray.push(newQuantityEntry);
        expectedPriceForEachArray.push(newExpectedPriceforEachEntry);
  }
  for(var i=0; i<itemArray.length;i++)
  {
    var row = table.insertRow();
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    cell1.innerHTML = itemArray[i];
    cell2.setAttribute('style', 'text-align: right;');
    cell2.innerHTML = quantityArray[i];
    cell3.setAttribute('style', 'text-align: right;');
    cell3.innerHTML = expectedPriceForEachArray[i] + " USD";
  }
}   
</script>

<body>
    <h1>
        Enter an item, quantity, and the price you're expecting to pay.
    </h1>
    Item:<br>
    <br>
    <input type="text" placeholder="ketchup" id="itemForm">
    <br>
    <br> Quantity:
    <br>
    <br>
    <input type="number" placeholder="25" id="quantityForm">
    <br>
    <br> Expected Price for Each:<br>
    <br>
    <input type="number" placeholder="2.99" id="expectedPriceForEachForm">
    <br>
    <br>

    <button onclick="addToListOfEntries()">Add this entry to the list</button>
    <br>
    <br>
    <table id="myEntries" border='1' width='400'>
        <tr>
            <th>Item</th>
            <th>Quantity</th>
            <th>Expected Price For Each</th>
        </tr>
    </table>
</body>

</html>

答案 1 :(得分:0)

使用Javascript对象而不是三个不同的数组来记录您的条目:

// a sample item: 
var item = {
   name: "something",
   quantity: 5,
   price: 4.99
};

// a sample cart: 
var cartItems = [
    {name: "Tomato", quantity: 5, price: 2.99},
    {name: "Potato", quantity: 6, price: 5.99}
];

// Now you can easily add them in the HTML:
for(var i=0; i<cartItems.length;i++)
{
    cell1.innerHTML = cartItems[i].name;
    cell2.setAttribute('style', 'text-align: right;');
    cell2.innerHTML = cartItems[i].quantity;
    cell3.setAttribute('style', 'text-align: right;');
    cell3.innerHTML = cartItems[i].price + " USD";
}

// And you can also comapare them like this: 
  for (var i=0; i < cartItems.length; i++) {
      if (itemArray[i].name === newItemEntry) {
        cartItems[i].quantity += newQuantityEntry; // we add the quantity to the existing.
        cartItems[i].price = (cartItems[i].price + newExpectedPriceForEachEntry) / 2; // We average the price.
      } else {
          // else you push that item as a new object: 
          cartItems.push({
               name: newItemEntry,
               quantity: newQuantityEntry,
               price: newExpectedPriceForEachEntry
          });
      }
  }; 

答案 2 :(得分:0)

@dlac是正确的,但是在最后一步中,我将使用索引,因为您也必须更新表。

var items = [];

function addNewItem()
{
  var table = document.getElementById("myEntries");
  var row = table.insertRow();
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);
  var item = 
    {
      name : document.getElementById("itemForm").value,
      quantity: parseInt(document.getElementById("quantityForm").value),
      price : parseInt(document.getElementById("expectedPriceForEachForm").value)
      
    };
    
  items.push( item );
  
  cell1.innerHTML = item.name;
  cell2.setAttribute('style', 'text-align: right;');
  cell2.innerHTML = item.quantity;
  cell3.setAttribute('style', 'text-align: right;');
  cell3.innerHTML = item.price + " USD";
  
}

function updateItem(item)
{
  var idx = items.indexOf(item);
  items[idx].price +=  parseInt(document.getElementById("expectedPriceForEachForm").value);
  items[idx].quantity +=  parseInt(document.getElementById("quantityForm").value);
              document.getElementById("myEntries").rows[idx+1].cells[2].innerHTML = items[idx].price + " USD";
              document.getElementById("myEntries").rows[idx+1].cells[1].innerHTML = items[idx].quantity;
  
}

function addToListOfEntries () {
  
  var possibleUpdateItem = items.find(function(element) {
    return element.name == document.getElementById("itemForm").value;
  });
  
  if(possibleUpdateItem)
  {
    updateItem(possibleUpdateItem); 
  }else
  {
    addNewItem();
  }
  
}
    <h1>
        Enter an item, quantity, and the price you're expecting to pay.
    </h1>
    Item:<br>
    <br>
    <input type="text" placeholder="ketchup" id="itemForm">
    <br>
    <br> Quantity:
    <br>
    <br>
    <input type="number" placeholder="25" id="quantityForm">
    <br>
    <br> Expected Price for Each:<br>
    <br>
    <input type="number" placeholder="2.99" id="expectedPriceForEachForm">
    <br>
    <br>

    <button onclick="addToListOfEntries()">Add this entry to the list</button>
    <br>
    <br>
    <table id="myEntries" border='1' width='400'>
        <tr>
            <th>Item</th>
            <th>Quantity</th>
            <th>Expected Price For Each</th>
        </tr>
    </table>