为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

神不在的星期二 2022-08-04 09:54:00
我创建了一个名为的类,该类具有属性之一。当用户按“添加”时,产品将被添加到名为 的数组中。因此,我尝试将数组中每个对象的总成本相加,以获得子总和。但它只将代码写出屏幕。producttotalcostproductsvar 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;    }  }}
查看完整描述

2 回答

?
蓝山帝景

TA贡献1843条经验 获得超7个赞

我为你创造了一个例子。您可以使用以下代码获取产品列表的小计


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))


查看完整回答
反对 回复 2022-08-04
?
慕村9548890

TA贡献1884条经验 获得超4个赞

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


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;

    }


    }


查看完整回答
反对 回复 2022-08-04
  • 2 回答
  • 0 关注
  • 199 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号