亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我的代碼不允許我在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 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號