javascript - 运行时收到许多未定义的调用,每个函数都说它是未定义的
问题描述
我到处都得到未定义的值,这很烦人。我相信我用 const 设置输入的方式可能是个问题
const prod = new Product();
prod
或者是别的什么 ?我相信已经尝试修复一些功能,例如将其返回以购买产品并将我的 toLowerCase 修复为 null。
var products = [];
class Product {
constructor(productName, amount, cost) {
this.productName = productName,
this.amount = amount,
this.cost = cost
}
buyProduct(product){
products.push(product);
return this;
}
deleteProduct(str){
var found = products.find(function(element){
})
if(found)
{
if(found.amount>1)
}
}
}
解决方案
您并没有this
从所有方法中返回,因此您不能将所有方法都链接起来。
sumPrice()
仅在找到该项目时才返回deleteProduct()
不返回这个sumTotal()
两者都不
此外,您的代码被严重破坏。这是我为使其正常工作而进行的修复的列表:
- 在所有方法中返回 this。
amount
对and使用相同的属性名称quantity
item
对and使用相同的属性名称productName
amount
对and使用数字而不是字符串cost
- 删除构造函数,它从未被调用
- 使用
let/const
而不是var
我还将类的名称更改为Product
,ProductsStore
因为您的类管理您的所有产品,而不仅仅是一个,因此我将products[]
数组移动到类中并在构造函数中对其进行了初始化。
class ProductsStore {
constructor() {
this.products = [];
}
buyProduct(product) {
this.products.push(product);
return this;
}
deleteProduct(str) {
const found = this.products.find(el =>
el.productName.toLowerCase() == str.toLowerCase())
if (found) {
if (found.amount > 1) {
const foundIndex = this.products.findIndex(x => x.productName.toLowerCase() === str.toLowerCase());
this.products[foundIndex].amount = found.amount - 1;
} else {
this.products.splice(this.products.findIndex(
item => item.productName.toLowerCase() === str.toLowerCase()), 1)
}
}
return this;
}
sumPrice(str, num) {
const foundIndex = this.products.findIndex(x => (x.productName || '').toLowerCase() === str.toLowerCase());
if (foundIndex >= 0) {
this.products[foundIndex].cost = this.products[foundIndex].cost + num;
}
return this;
}
sumTotal() {
this.total = 0;
for (let obj of this.products) {
this.total += obj.amount * obj.cost;
}
return this;
}
write() {
let total = 0;
for (let obj of this.products) {
console.log('Item: ' + obj.productName + ' | Quantity:' + obj.amount + ' | Price:' + obj.cost);
total += obj.amount * obj.cost;
}
console.log('$' + total);
}
}
new ProductsStore()
.buyProduct({ productName: 'jameson', amount: 1, cost: 0 })
.buyProduct({ productName: 'bud light', amount: 3, cost: 0 })
.buyProduct({ productName: 'corona', amount: 4, cost: 0 })
.buyProduct({ productName: 'beer', amount: 1, cost: 0 })
.sumPrice('tequila', 5.99)
.deleteProduct('corona')
.sumPrice('beer', 5.04)
.sumTotal()
.write();
推荐阅读
- javascript - 如果 Key 存在于也包含数组的 JavaScript 对象中,则查找并返回值
- javascript - 如何通过javascript在洗牌后恢复元素的顺序?
- facebook - Facebook - API 转换和像素 - 重复问题
- javascript - 打字稿继承 - 将类型为父类的变量设置为子类
- javascript - 使用 React Router 时如何错误捕获“无法读取未定义的属性‘链接’”?
- python - 当使用 Autokey 按下某个键时,如何停止 while 循环?
- python - 是否可以在 Python 中向基于 Selenium 的应用程序添加用户界面?
- postgresql - psql:致命:用户“” aws rds Postgresql 的 PAM 身份验证失败
- c# - View 返回 null 给控制器,接受 ViewModel
- c# - TPL 数据流,如果 BoundedCapacity 已满,如何丢弃以前的(第一条)消息