Javascript 为什么我的代码不允许我在js中同时添加两个对象属性?
我创建了一个名为Javascript 为什么我的代码不允许我在js中同时添加两个对象属性?,javascript,arrays,object,properties,Javascript,Arrays,Object,Properties,我创建了一个名为product的类,它将totalcost作为属性之一。当用户按下“添加”按钮时,产品将被添加到名为products的数组中。因此,我尝试将数组中每个对象的总成本相加,以得到小计。但它只在屏幕上写出代码 var subtotal = subtotal(); function subtotal() { if (products.length == 1) { subtotal = totalcost; return subtotal; } else if (
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;
}
}
}
var小计=小计();
函数小计(){
如果(products.length==1){
小计=总成本;
返回小计;
}否则如果(products.length>1){
对于(i=0;i
请尝试以下代码以添加所有产品总成本
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;
}
}
函数小计(){
var合计=0;
如果(products.length==1){
总成本=总成本;
返回总数;
}
否则如果(products.length>1){
对于(var i=0;i我已经为您创建了一个示例。您可以使用下面的代码来获取产品列表的小计
listproducts=[{totalcost:50},{totalcost:30},{totalcost:150}];
职能小计(产品){
小计=0;
如果(products.length==0){
返回0;
}
对于(i=0;它看起来不像java,它看起来像js。此外,您还没有在任何地方声明i
或subtotal
,这在两种语言中都是一个错误。谢谢。我只需对此进行一些编辑,它就可以工作了。if块是不必要的。