如何在数组中添加值,然后输出到计算函数?

时间:2015-10-01 11:17:49

标签: javascript

我是Javascript的新手。我的问题是 - 如何在这样的数组中添加值:

var pizza = {
    Hawaiianvalue: 9.50,
    Cheesevalue: 9.50,
    Veggievalue: 9.50,
    Supremevalue: 9.50,
    Pepperonivalue: 9.50,
    MeatLoversvalue: 15.50,
    Chicken: 15.50,
    Prawnvalue: 15.50
};

然后将这些值输出到类似于此的函数:

function calculateTotalPrice(e){ 
var calc = (Hawaiianvalue + Cheesevalue + Veggievalue + Supremevalue + Pepperonivalue
    + MeatLoversvalue + Chickenvalue + Prawnvalue);
output1.value = calc; }

提前致谢:)

1 个答案:

答案 0 :(得分:0)

使用 for...in 循环迭代对象



var pizza = {
  Hawaiianvalue: 9.50,
  Cheesevalue: 9.50,
  Veggievalue: 9.50,
  Supremevalue: 9.50,
  Pepperonivalue: 9.50,
  MeatLoversvalue: 15.50,
  Chicken: 15.50,
  Prawnvalue: 15.50
};

function calculateTotalPrice(e) {
  var calc = 0;
  for (var key in pizza) {
    if (pizza.hasOwnProperty(key))
      calc += pizza[key];
  };
  console.log(calc);
  return calc;
}

calculateTotalPrice();