gpt4 book ai didi

javascript - 收银机初级 Javascript 项目

转载 作者:行者123 更新时间:2023-11-27 23:57:14 24 4
gpt4 key购买 nike

我刚刚开始令人兴奋的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com