1

I have stacked in the sum of an array. 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", "[email protected]");
    console.log(athar.name);
    athar.changeEmail("[email protected]");
    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?

2
  • Return is perform early man! Commented Jun 28, 2016 at 8:35
  • 17
    How is this a Hot Network Question? Commented Jun 28, 2016 at 11:24

6 Answers 6

11

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

7

Using Array.prototype.reduce() you can simplify that function a lot:

intotal: function() {
  return this.cartAmount.reduce((a, b)=> a + b)
}

From MDN:

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

Here you pass an arrow function to the reduce method, which takes two arguments: a and b, and returns sum of them.

Comments

7

Do not use this.total for that. If you call this method several times, your total will increase each time you call it. You should at least put a this.total = 0 at the top of your method.

I personally would have written it like this instead :

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

    return out;
}

Comments

4

intotal function returning the first element of cartAmount array. Place the return statement of intotal function outside of for loop.

Comments

0

function sum(){
 var args = Array.prototype.slice.call(arguments);
 return args.reduce(function(pre,curr){
   if(!isNaN(curr)){
     return pre+curr;
   }
   else
   {
    throw Error("Non-Numeric arguments"+curr);
   }
},0)
}
    var result = sum(12,13,14); //pass any number of parameter to sum
    alert("Sum Is:"+result);

Comments

0

https://www.npmjs.com/package/mnjs

First import sum function from mnjs package

<script src="https://cdn.jsdelivr.net/npm/mnjs/browser/index.js"></script>

or

const { sum } = require('mnjs')

or

import { sum } from 'mnjs'

Then use sum function as follow:

const cartAmount = [1, 4, 2]

sum(cartAmount)   // returns 7

https://runkit.com/dr-montasir/mnjs-sum-function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.