首页 > 解决方案 > 运行时收到许多未定义的调用,每个函数都说它是未定义的

问题描述

我到处都得到未定义的值,这很烦人。我相信我用 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)

           }
       }
   }




标签: javascript

解决方案


您并没有this从所有方法中返回,因此您不能将所有方法都链接起来。

  • sumPrice()仅在找到该项目时才返回
  • deleteProduct()不返回这个
  • sumTotal()两者都不

此外,您的代码被严重破坏。这是我为使其正常工作而进行的修复的列表:

  • 在所有方法中返回 this。
  • amount对and使用相同的属性名称quantity
  • item对and使用相同的属性名称productName
  • amount对and使用数字而不是字符串cost
  • 删除构造函数,它从未被调用
  • 使用let/const而不是var

我还将类的名称更改为ProductProductsStore因为您的类管理您的所有产品,而不仅仅是一个,因此我将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();


推荐阅读