JavaScript和函数

jam*_*har -1 javascript arrays loops return sum

我已经堆叠在一个数组的总和.代码如下

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());
Run Code Online (Sandbox Code Playgroud)

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

hai*_*770 10

return太早了,因此你的for循环只运行一次并返回购物车中的第一项.

试试这个:

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

    return this.total;
    }
Run Code Online (Sandbox Code Playgroud)


xur*_*rei 7

不要用this.total它.如果您多次调用此方法,则每次调用此方法时总计会增加.你应该至少把a this.total = 0放在你的方法的顶部.

我本人会这样写的:

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

    return out;
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*ski 6

使用Array.prototype.reduce()您可以大大简化该功能:

intotal: function() {
  return this.cartAmount.reduce((a, b)=> a + b)
}
Run Code Online (Sandbox Code Playgroud)

来自 MDN:

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

在这里,您将一个箭头函数传递给该reduce方法,该方法接受两个参数:aand b,并返回它们的总和。