2016-06-28 67 views
0

我堆积了一个数组的总和。代码是波纹管JavaScript总和函数

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

它显示我只有20作为总和的结果。问题是什么?

+0

回报是进行早期人类! –

+15

这是一个热门网络问题? – immibis

回答

11

您的return太早,因此您的for循环只运行一次并返回购物车中的第一个项目。

尝试此代替:

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

    return this.total; 
    } 
4

intotal函数返回cartAmount阵列的第一个元素。 将intotal函数的return语句放在for循环之外。

7

不要使用this.total。如果您多次调用此方法,每次调用它时总数都会增加。您至少应该在方法的顶部放置一个this.total = 0

我个人会写像这样代替:

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

    return out; 
} 
3

使用Array.prototype.reduce()可以简化功能很多:

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

从MDN:

reduce()方法针对累加器应用函数和数组的每个值(从左到右)将其减少为单个值。

在这里你传递一个arrow functionreduce方法,它有两个参数:ab,并返回它们的总和。

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