【问题标题】:Why is my code not allowing me to add two object properties together in js?为什么我的代码不允许我在 js 中一起添加两个对象属性?
【发布时间】:2020-05-06 18:59:57
【问题描述】:

我创建了一个名为product 的类,其中totalcost 作为属性之一。当用户按下“添加”时,产品将被添加到名为products 的数组中。所以,我试图添加数组中每个对象的总成本来获得小计。但它只会将代码写出屏幕。

var subtotal = subtotal();

function subtotal() {
  if (products.length == 1) {
    subtotal = totalcost;
    return subtotal;
  } else if (products.length > 1) {
    for (i = 0; i < products.length; i++) {
      subtotal += products[i].totalcost + products[i + 1].totalcost;
      return subtotal;
    }
  }
}

【问题讨论】:

  • 这看起来不像java,看起来像js。此外,您还没有在任何地方声明 isubtotal,这在两种语言中都是一个错误

标签: javascript arrays object properties


【解决方案1】:

我为您创建了一个示例。您可以使用以下代码获取产品列表

的小计

listproducts=[{totalcost:50},{totalcost:30},{totalcost:150}];
function FnSubtotal(products){
  subtotal=0;
  if(products.length == 0){
     return 0;
  }
  for(i = 0; i<products.length; i++){
      subtotal += products[i].totalcost;   
  }
  return subtotal;
};
console.log(FnSubtotal(listproducts))

【讨论】:

  • 不需要 if 块。
【解决方案2】:

请尝试以下代码来添加所有产品总成本

function subtotal(){
var total=0;
    if(products.length == 1){
        total = totalcost;
        return total;
    }

    else if(products.length > 1){
        for(var i = 0; i<products.length; i++){
            total += products[i].totalcost;

    }
return total;
    }

    }

【讨论】:

  • 谢谢。我只需要对此进行一些编辑即可。
猜你喜欢
  • 2014-10-17
  • 2019-08-03
  • 1970-01-01
  • 2013-05-20
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
相关资源
最近更新 更多