2016-06-28 68 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);