总计NaN的项目

时间:2012-08-28 17:45:21

标签: javascript

我正在开发一个codecademy.com教程,我们正在建立一个收银机。我应该制作必要的工具来取消收银机的最后一笔交易。因此,我添加了

  1. 一个名为lastTransactionAmount的属性
  2. 函数'add'的另一行代码,用于设置最后一笔交易金额
  3. 函数voidLastTransaction数量,用于从总计
  4. 中减去最后一个事务
  5. 然后我测试了底部的void last transaction函数(我希望这四个巧克力无效
  6. 然后我尝试添加三个巧克力
  7. 当我运行代码时,我得到了

      

    你的账单是NaN

    有人可以解释我做错了什么吗?

    var cashRegister = {
        total:0,
        //Dont forget to add your property
        lastTransactionAmount: 0,         //this is a property I added
    
        add: function(itemCost) {
            this.total +=  itemCost;
            this.lastTransactionAmount = this.itemCost; //I added this to save 
        },
        scan: function(item,quantity) {
            switch (item) {
            case "eggs": this.add(0.98 * quantity); break;
            case "milk": this.add(1.23 * quantity); break;
            case "magazine": this.add(4.99 * quantity); break;
            case "chocolate": this.add(0.45 * quantity); break;
            }
            return true;
        },
        //Add the voidLastTransaction Method here // I made this function to void l
        voidLastTransaction: function() {
            this.total = this.total - this.lastTransactionAmount; 
        }
    };
    
    cashRegister.scan('eggs',1);
    cashRegister.scan('milk',1);
    cashRegister.scan('magazine',1);
    cashRegister.scan('chocolate',4);
    
    //Void the last transaction and then add 3 instead
    cashRegister.voidLastTransaction();              //I'm voiding last transaction
    cashRegister.scan('chocolate', 3);             //trying to add 3 (instead of 4)chocolate
    
    //Show the total bill
    console.log('Your bill is '+cashRegister.total);
    

1 个答案:

答案 0 :(得分:5)

itemCost中没有属性cashRegister。它应该是this.lastTransactionAmount = itemCost;