为什么我的代码不允许我在js中同时添加两个对象属性?

我创建了一个名为的类,该类具有属性之一。当用户按“添加”时,产品将被添加到名为 的数组中。因此,我尝试将数组中每个对象的总成本相加,以获得子总和。但它只将代码写出屏幕。producttotalcostproducts


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;

    }

  }

}


神不在的星期二
浏览 200回答 2
2回答

蓝山帝景

我为你创造了一个例子。您可以使用以下代码获取产品列表的小计listproducts=[{totalcost:50},{totalcost:30},{totalcost:150}];function FnSubtotal(products){&nbsp; subtotal=0;&nbsp; if(products.length == 0){&nbsp; &nbsp; &nbsp;return 0;&nbsp; }&nbsp; for(i = 0; i<products.length; i++){&nbsp; &nbsp; &nbsp; subtotal += products[i].totalcost;&nbsp; &nbsp;&nbsp; }&nbsp; return subtotal;};console.log(FnSubtotal(listproducts))

慕村9548890

请尝试以下代码来添加所有产品总成本function subtotal(){var total=0;&nbsp; &nbsp; if(products.length == 1){&nbsp; &nbsp; &nbsp; &nbsp; total = totalcost;&nbsp; &nbsp; &nbsp; &nbsp; return total;&nbsp; &nbsp; }&nbsp; &nbsp; else if(products.length > 1){&nbsp; &nbsp; &nbsp; &nbsp; for(var i = 0; i<products.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; total += products[i].totalcost;&nbsp; &nbsp; }return total;&nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript