jamil athar jamil athar - 5 months ago 24
Javascript Question

JavaScript basic math

I am learning OOP of javascript now. I have stacked in the sum of an array. Please help me. The code is bellow

function User(name,email){
this.name = name;
this.email = email;
this.cartAmount=[];
this.total=0;
}
User.prototype={
constructor:User,

addCart: function(mrp){
this.cartAmount.push(mrp);
},

changeEmail: function(newmail){
this.email=newmail;
},

showCart: function(){
var cart= this.cartAmount.length >0 ? this.cartAmount.join("tk,") : "No product in the cart";
return this.name+" has "+cart+" in his cart.";
},

intotal: function(){
for(var n in this.cartAmount){
this.total += this.cartAmount[n];
return this.total;
}
}
};
athar= new User("Athar Jamil", "atharjamil@gmail.com");
console.log(athar.name);
athar.changeEmail("atharjamil@yahoo.com");
console.log(athar.email);
athar.addCart(20);
athar.addCart(50);
athar.addCart(80);
console.log(athar.intotal());


It shows me only 20 as the result of the sum. What is the problem?

Answer

You're returning too early, hence your for loop runs only once and returns the first item in the cart.

Try this instead:

 intotal: function(){
    for(var n in this.cartAmount){
        this.total += this.cartAmount[n];
    }

    return this.total;
    }
Comments