我刚刚开始学习Javascript的令人兴奋的旅程,在我的一堂课中,我被要求构建一个voidLastTransaction方法来添加到我的虚拟收银机中。我已经写出了代码,该代码允许用户从上次交易中扣除金额。但是,我想知道如何做才能使最后两笔交易无效,而不是一笔交易。我想在我想要作废的每个事务之后调用该函数是一种实现方法。但我想知道是否有一种更动态的方式来重置存储最后一笔交易的金额的属性,以使它更改为列表中上一笔交易的值,这将成为最后一笔下一笔“最后一笔交易”交易已扣除。下面是我当前的代码。提前致谢!

var cashRegister = {
total: 0,
lastTransactionAmount: 0,
add: function(itemCost) {
   this.total += itemCost;
   this.lastTransactionAmount = itemCost;
},
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;
},

voidLastTransaction: function() {
  this.total -= this.lastTransactionAmount;
  this.lastTransactionAmount = 0;
}
};

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

// I want to void the last 2 transactions
console.log("your bill is" + cashRegister.total);

最佳答案

我将使用数组,这样可以更轻松地获取最后一笔交易并将项目应用于总计。阵列是顺序的这一事实是跟踪添加的交易的理想候选者。而且,JavaScript数组可以轻松地用作堆栈或队列。

我已将您的lastTransactionAmount替换为交易:[]

以下未经测试,因此可能是越野车:

var cashRegister = {
total: 0,

// use array instead,
// for the problem in question it will function as a stack
transactions:[],

add: function(itemCost) {
   this.total += itemCost;
   this.transactions.push(itemCost); // add each item to array
},

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;
},

  voidLastTransaction: function(total) {
    // the immediately following single operation, get's the last element
    // in the array (stack), which coincides with the last recorded transaction
    // and at the same time, it removes the element from the stack!
    // So every time this method is called you have one less transaction.
    var lastTransactionCost = this.transactions.pop();
    this.total -= lastTransactionCost;
  }
};

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

console.log("Current outstanding total: " + cashRegister.total);

console.log("About to void the last 3 transactions...");

var numberOfTransactionsToCancel = 3;
while(numberOfTransactionsToCancel--){
    cashRegister.voidLastTransaction();
};

09-17 09:24