作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我刚刚开始令人兴奋的 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();
};
关于javascript - 收银机初级 Javascript 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32160070/
我正在为圣诞树构建一个收银机应用程序。我希望能够进行多个事务,这样我就可以跟踪正在进行的树的数量。问题是我可以做一笔交易,然后就结束了。我考虑过使用 while 循环,但也许我做错了,因为它创建了一个
我是一名优秀的程序员,十分优秀!