这是我的代码:
var arr = [];
class Art {
constructor() {
this.values = Array();
}
add(date, amount, currency, product) {
this.values.push([date, amount, currency, product].toString());
}
list() {
return this.values;
}
clear(date) {
for (let i = this.values.length - 1; i >= 0; --i) {
if (this.values[i][0] == date) {
this.values.splice(i, 1);
}
}
}
total() {
return this.values[this.amount + this.currency];
}
}
const art = new Art();
art.add('2017-04-25', 2, 'USD', 'Jogurt');
art.add('2017-04-25', 3, 'USD', 'French fries');
art.add('2017-04-27', 4.75, 'USD', 'Beer');
art.clear('2017-04-27');
console.log(art.list());
console.log(art.total());
total();应该返回我添加到art.add中的金额和货币。但是它输出未定义。我已经尽力了。但所有的时间我都没有定义或NaN。请你帮助我好吗?
答案 0 :(得分:2)
您需要将值存储在数组中,而不是数据数组的字符串表示形式。
要保留数量,可以在插入新数据集时添加它,也可以在拼接项目时删除该值。
this.totals
被实现为对象,以货币作为键,值作为金额。
class Art {
constructor() {
this.values = Array();
this.totals = Object.create(null);
}
add(date, amount, currency, product) {
this.totals[currency] = this.totals[currency] || 0;
this.totals[currency] += amount;
this.values.push([date, amount, currency, product]); //.toString());
}
list() {
return this.values;
}
clear(date) {
var amount, currency;
for (let i = this.values.length - 1; i >= 0; --i) {
if (this.values[i][0] == date) {
[, amount, currency] = this.values.splice(i, 1)[0]
this.totals[currency] -= amount;
}
}
}
total() {
return this.totals;
}
}
const art = new Art();
art.add('2017-04-25', 2, 'USD', 'Jogurt');
art.add('2017-04-25', 3, 'USD', 'French fries');
art.add('2017-04-27', 4.75, 'USD', 'Beer');
art.clear('2017-04-27');
console.log(art.list());
console.log(art.total());