【发布时间】:2022-02-21 11:04:23
【问题描述】:
我的测试应用程序几乎完成了,但是当我从购物车中取出一个“苹果”并且数量变为 2 个时,我似乎无法改变三个苹果时的价格/总量。
这可能与构造函数类有关,但我对使用它还是比较陌生,所以我在解决这个问题时遇到了一些麻烦。
在控制台日志中,我基本上希望总金额反映苹果的数量(现在是 2 个)。
module.exports = {
shoppingCart: function () {
//create empty cart array
theCart = [];
// create two seperate versions of the same kind of object using class method
class Fruits {
constructor(fruit, price, quantity) {
this.fruit = fruit;
this.quantity = quantity;
this.price = price * quantity--;
}
}
let fruit1 = new Fruits("Apple", 4.95, 3); // create new object. sets the value of this
if (fruit1.quantity === 3) {
fruit1.quantity--;
}
let bothFruits = [fruit1];
//add items to the cart
Array.prototype.push.apply(theCart, bothFruits);
let total = fruit1.price + " = total amount.";
//function to add items to the cart
function removeAllItems() {
if (theCart.length = !0) {
theCart = [];
}
}
//removeAllItems();
console.log(theCart, total);
}
}
【问题讨论】:
标签: javascript node.js arrays object