Why it doesn't work?


#1

Hello guys! Please help me

Is it incorrect??? But how? The result is correct!

var cashRegister = {
    total:0,
    add: function(itemCost){
        this.total += itemCost;
    },
    scan: function(item, quantity) {
        for(var i = quantity; i > 0; i--) {
            switch (item) {
        case "eggs": this.add(0.98); break;
        case "milk": this.add(1.23); break;
        case "magazine": this.add(4.99); break;
        case "chocolate": this.add(0.45); break;
        }
        }
        
    }
};

cashRegister.scan("eggs", 4)
cashRegister.scan("milk", 4)
cashRegister.scan("magazine", 4)
cashRegister.scan("chocolate", 4)

//Show the total bill
console.log('Your bill is '+cashRegister.total);

Screenshot:
http://hpics.li/93d97ed


#2

your function is correct but "quantity" is not using correctly
you can do this without for loop and i think it's a easy way to do this.
like
case "eggs": this.add(0.98*quantity ); break;
ok?
because of for loop your result is same what should be.But it will take much more time than it.

@anyonjs


#3

I agree with @rcodeman.

Remove the for loop from scan and keep the switch statement like this:

scan: function(item, quantity) {
     switch (item) {
           case "eggs": this.add(0.98); break;
          case "milk": this.add(1.23); break;
          case "magazine": this.add(4.99); break;
          case "chocolate": this.add(0.45); break;
           }
        },

#4

NOW do (price * quantity) for each item
like
0.98*quantity

ok?
@mamayama


#5

Thanks all of you guys for the answers. Yesterday i had done it myself before i read the answers. I agree that is more easy and more readable solution. But i think the developers can add my case.