Javascript-遍历循环对象后尝试将它们添加在一起

时间:2018-08-27 17:05:51

标签: javascript jquery arrays shopping-cart checkout

我正在尝试进行迷你签出JavaScript练习。用户将2个或多个项目加在一起(checkbox)选项,将这些项目的价格合计然后返回。由于某种原因,我无法将数组对象的值加在一起。我代码中的所有其他内容仅在那一部分起作用。有人可以帮帮我吗?我的代码如下:

JavaScript

// This Array Object holds the items name and prices the user selects from
var shoppingItems = {
  "Stainless Steel Cooking Pot": 29.99,
  "Mini Stainless Steel Blender": 19.99,
  "Kitchen Towel Set": 7.99,
  "Large Tan Coffee Mug": 5.49,
  "5 Round Dinner Plate Set": 5.99,
  "Salt and Pepper Shaker Set": 1.99,
  "Large Blue Broom": 3.98,
  "Pink Soap Dish": 2.50,
  "Silver Bathroom Trash Can": 6.99,
  "Silk Black Bathroom Robe": 9.99,
};

var itemsSelectedValues = [];
// this is the empty array where the checkbox values will be added to

var total = 0;
 // this is the variable that will hold the items total

function listOfCheckedItems(catalogToLookFrom) {
  var yourItemsPurchased = $("input:checkbox:checked");
  for (i = 0; i < yourItemsPurchased.length; i++) {
      if(yourItemsPurchased[i].checked === true) {
       itemsSelectedValues.push(yourItemsPurchased[i].value);
      } // line closes if statement
  } // line closes for loop
  for (i = 0; i < itemsSelectedValues.length; i++) {
    // line above is suppose to loop through the now full array that has the items value names stored
    total = total + catalogToLookFrom[itemsSelectedValues];
    // this line is suppose to set variable total to itself + the value of the item that's stored in array shoppingItems. It's suppose to do this each time through the loop. This is where the problem lies. 
  } // closes for loop
  console.log(catalogToLookFrom[itemsSelectedValues]);
  return total;
} // line closes listOfCheckedItems function

function getOrderTotal() {
  listOfCheckedItems(shoppingItems);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="cash-register.html" method="post">
    <p style="color:#A569BD; font-size:20px; text-decoration:underline; margin-left:20px;">Department Store Items</p>
    <input type="checkbox" name="products[]" value="Stainless Steel Cooking Pot">Stainless Steel Cooking Pot - $29.99<br>
    <input type="checkbox" name="products[]" value="Mini Stainless Steel Blender">Mini Stainless Steel Blender - $19.99<br>
    <input type="checkbox" name="products[]" value="Kitchen Towel Set">Kitchen Towel Set - $7.99<br>
    <input type="checkbox" name="products[]" value="Large Tan Coffee Mug">Large Tan Coffee Mug - $5.49<br>
    <input type="checkbox" name="products[]" value="5 Round Dinner Plate Set">5 Round Dinner Plate Set - $5.99<br>
    <input type="checkbox" name="products[]" value="Salt and Pepper Shaker Set">Salt and Pepper Shaker Set - $1.99<br>
    <input type="checkbox" name="products[]" value="Large Blue Broom">Large Blue Broom - $3.98<br>
    <input type="checkbox" name="products[]" value="Pink Soap Dish">Pink Soap Dish - $2.5<br>
    <input type="checkbox" name="products[]" value="Silver Bathroom Trash Can">Silver Bathroom Trash Can - $6.99<br>
    <input type="checkbox" name="products[]" value="Silk Black Bathroom Robe">Silk Black Bathroom Robe - $9.99
    <br/>
    <br/>
    <button type="button" name="yourOrder" onclick="getOrderTotal()">Submit</button>
    <br/>
    <br/>
</form>

3 个答案:

答案 0 :(得分:2)

您忘记了循环中的[i]

total = total + catalogToLookFrom[itemsSelectedValues[i]];

这是一个简化的版本

$(function() { // when the page loads
  $("input:checkbox").on("change", function() { // each time something changes
    var total = 0;
    $("input[type=checkbox]:checked").each(function() { // only checked boxes
      total += shoppingItems[this.value]; // the prices are already numbers
    })
    $("#total").text(total.toFixed(2)); // 2 decimals
  }).change(); // run at load time to calculate
})

// This Array Object holds the items name and prices the user selects from
var shoppingItems = {
  "Stainless Steel Cooking Pot": 29.99,
  "Mini Stainless Steel Blender": 19.99,
  "Kitchen Towel Set": 7.99,
  "Large Tan Coffee Mug": 5.49,
  "5 Round Dinner Plate Set": 5.99,
  "Salt and Pepper Shaker Set": 1.99,
  "Large Blue Broom": 3.98,
  "Pink Soap Dish": 2.50,
  "Silver Bathroom Trash Can": 6.99,
  "Silk Black Bathroom Robe": 9.99,
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="cash-register.html" method="post">
  <p style="color:#A569BD; font-size:20px; text-decoration:underline; margin-left:20px;">Department Store Items</p>
  <input type="checkbox" name="products[]" value="Stainless Steel Cooking Pot">Stainless Steel Cooking Pot - $29.99<br>
  <input type="checkbox" name="products[]" value="Mini Stainless Steel Blender">Mini Stainless Steel Blender - $19.99<br>
  <input type="checkbox" name="products[]" value="Kitchen Towel Set">Kitchen Towel Set - $7.99<br>
  <input type="checkbox" name="products[]" value="Large Tan Coffee Mug">Large Tan Coffee Mug - $5.49<br>
  <input type="checkbox" name="products[]" value="5 Round Dinner Plate Set">5 Round Dinner Plate Set - $5.99<br>
  <input type="checkbox" name="products[]" value="Salt and Pepper Shaker Set">Salt and Pepper Shaker Set - $1.99<br>
  <input type="checkbox" name="products[]" value="Large Blue Broom">Large Blue Broom - $3.98<br>
  <input type="checkbox" name="products[]" value="Pink Soap Dish">Pink Soap Dish - $2.5<br>
  <input type="checkbox" name="products[]" value="Silver Bathroom Trash Can">Silver Bathroom Trash Can - $6.99<br>
  <input type="checkbox" name="products[]" value="Silk Black Bathroom Robe">Silk Black Bathroom Robe - $9.99
  <br/>
  <br/>
  <button type="button" name="yourOrder">Submit</button>
  <br/>
  <br/>
</form>
Total: $<span id="total"></span>

答案 1 :(得分:1)

您可以在此处使用其他更简洁的逻辑。

使用jQuery选择元素后,可以使用period_x.append(sum_x)遍历这些对象,其中.each()上下文将直接成为元素。

此外,您不需要带有值的数组,您可以简单地求和然后在this函数内部,将选择的值传递到each()的数组中。您检索$值的方式。在迭代结束时,您将获得总价值。

正如我的回答中所说,一旦在jQuery中选择了仅选中的项,就无需检查shoppingItems

请看看:

this.checked === true
var shoppingItems = {
  "Stainless Steel Cooking Pot": 29.99,
  "Mini Stainless Steel Blender": 19.99,
  "Kitchen Towel Set": 7.99,
  "Large Tan Coffee Mug": 5.49,
  "5 Round Dinner Plate Set": 5.99,
  "Salt and Pepper Shaker Set": 1.99,
  "Large Blue Broom": 3.98,
  "Pink Soap Dish": 2.50,
  "Silver Bathroom Trash Can": 6.99,
  "Silk Black Bathroom Robe": 9.99,
};

function listOfCheckedItems(catalogToLookFrom) {
  var yourItemsPurchased = $("input:checkbox:checked");
  var totalValue = 0;
  yourItemsPurchased.each(function(){      
      totalValue += parseFloat(shoppingItems[this.value]);
  }) 
  
  
  console.log(totalValue);
  return totalValue;
}

function getOrderTotal() {
  listOfCheckedItems(shoppingItems);
}

答案 2 :(得分:0)

您可以使用array.reduce将代码简化为一个内衬(请参见docs进行简化):

$("input:checkbox:checked").toArray().reduce((a, e) => a + catalog[e.value], 0)

这首先调用jQ集合上的toArray()将其转换为原始数组。在此数组上调用的reduce函数将数组(e)中的每个元素传递到回调函数中。 reduce还接受第二个参数0,该参数会累积最终总数。此总数反复传递到a回调的reduce参数中,并添加到从e对象获取的每个catalog值中。

var shoppingItems = {
  "Stainless Steel Cooking Pot": 29.99,
  "Mini Stainless Steel Blender": 19.99,
  "Kitchen Towel Set": 7.99,
  "Large Tan Coffee Mug": 5.49,
  "5 Round Dinner Plate Set": 5.99,
  "Salt and Pepper Shaker Set": 1.99,
  "Large Blue Broom": 3.98,
  "Pink Soap Dish": 2.50,
  "Silver Bathroom Trash Can": 6.99,
  "Silk Black Bathroom Robe": 9.99,
};

const listOfCheckedItems = catalog =>
  $("input:checkbox:checked").toArray().reduce((a, e) => a + catalog[e.value], 0)
; 

function getOrderTotal() {
  console.log(listOfCheckedItems(shoppingItems));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="cash-register.html" method="post">
  <p style="color:#A569BD; font-size:20px; text-decoration:underline; margin-left:20px;">Department Store Items</p>
  <input type="checkbox" name="products[]" value="Stainless Steel Cooking Pot">Stainless Steel Cooking Pot - $29.99<br>
  <input type="checkbox" name="products[]" value="Mini Stainless Steel Blender">Mini Stainless Steel Blender - $19.99<br>
  <input type="checkbox" name="products[]" value="Kitchen Towel Set">Kitchen Towel Set - $7.99<br>
  <input type="checkbox" name="products[]" value="Large Tan Coffee Mug">Large Tan Coffee Mug - $5.49<br>
  <input type="checkbox" name="products[]" value="5 Round Dinner Plate Set">5 Round Dinner Plate Set - $5.99<br>
  <input type="checkbox" name="products[]" value="Salt and Pepper Shaker Set">Salt and Pepper Shaker Set - $1.99<br>
  <input type="checkbox" name="products[]" value="Large Blue Broom">Large Blue Broom - $3.98<br>
  <input type="checkbox" name="products[]" value="Pink Soap Dish">Pink Soap Dish - $2.5<br>
  <input type="checkbox" name="products[]" value="Silver Bathroom Trash Can">Silver Bathroom Trash Can - $6.99<br>
  <input type="checkbox" name="products[]" value="Silk Black Bathroom Robe">Silk Black Bathroom Robe - $9.99
  <br/>
  <br/>
  <button type="button" name="yourOrder" onclick="getOrderTotal()">Submit</button>
  <br/>
  <br/>
</form>