【问题标题】:Javascript - trying to add array object values together after looping through themJavascript - 在遍历数组对象值后尝试将它们添加在一起
【发布时间】:2019-02-02 06:23:54
【问题描述】:

我正在尝试做一个小型结帐 JavaScript 练习。用户将 2 个或多个项目一起添加 (checkbox) 选项,项目的价格总计然后返回。出于某种原因,我无法将数组对象的值加在一起。我的代码中的其他所有内容都只适用于该 1 部分。有人可以帮帮我吗?我的代码如下:

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>

【问题讨论】:

  • 尝试将此行修改为total = total + Number(catalogToLookFrom[itemsSelectedValues]);
  • if(yourItemsPurchased[i].checked === true) { 是不必要的,因为该集合已经是检查项目
  • @Kapilgopinath 他们都是数字
  • @Kapilgopinath 非常感谢!
  • @mplungjan 非常感谢!

标签: javascript jquery arrays shopping-cart checkout


【解决方案1】:

你忘记了循环中的 [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>

【讨论】:

  • 好的,我明白了。我很抱歉。非常感谢。
  • 如果您需要更多解释,请告诉我@Aishah91
  • 我愿意。我很欣赏您的代码,但出于好奇,您知道为什么我的代码不起作用。看起来它在逻辑上是有道理的并且会起作用。只是想知道我哪里出错了。
  • 你需要total = total + catalogToLookFrom[itemsSelectedValues[i]];中的索引
  • @Aishah91 开心的时候请阅读:meta.stackexchange.com/questions/5234/…
【解决方案2】:

您可以在此处使用不同且更清晰的逻辑。

使用 jQuery 选择元素后,您可以使用 .each() 迭代这些对象,其中 thiscontext 将直接成为元素。

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

正如我在回答的 cmets 中所说,一旦你在 jQuery 中只选择了被检查的那些,你就不需要检查 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);
}
<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>

【讨论】:

  • 这个测试是不必要的if(this.checked === true) { totalValue += parseFloat(shoppingItems[this.value]); }
  • 你是对的,我把它放在后面是因为它在原始代码中,但现在它已经调整了。感谢您的提示!
  • @CalvinNunes 非常感谢!非常感谢
  • 很高兴知道我帮助了你。如果您认为这个答案是正确的,请在我的答案左侧加粗“V”标记
  • @Aishah91 请看我的回答。这不是我的代码!我的在这里:stackoverflow.com/a/52044201/295783
【解决方案3】:

您可以使用array.reduce 将您的代码简化为单行代码(请参阅docs 以了解reduce):

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

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

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>

【讨论】:

  • 这很可能对于新手 JS 分配来说太复杂了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
  • 2021-08-15
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多