我如何获得此代码以打印出此输出.我一直对.buyproduct不确定 [英] How do i get this code to print out this output. I keep getting undefined for .buyproduct

查看:74
本文介绍了我如何获得此代码以打印出此输出.我一直对.buyproduct不确定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此错误,我不确定如何解决.我想获得我在下面发布的预期输出,但需要使用点链.有人可以帮忙吗?

i get this error, im not sure how to fix it. I want to get the expected output i posted below but need to use dot chaining. Can anybody help?

.buyProduct({ item: 'bud light', quantity: '3'})
^                

TypeError: Cannot read property 'buyProduct' of undefined

    var products = [];
   class Product {
   constructor(productName, amount, cost) {
       this.productName = productName,
        this.amount = amount,
        this.cost = cost
    }

    buyProduct(product){
       products.push(product);
    }
    deleteProduct(str){
       var found = products.find(function(element){
           return (element.productName).toLowerCase() == 
    str.toLowerCase();
       })
       if(found)
       {
           if(found.amount>1)
           {
               var foundIndex = 
    products.findIndex(x=>x.productName.toLowerCase() === 
    str.toLowerCase());
               products[foundIndex].amount = found.amount-1;

           }
           else
           {

 products.splice(products.findIndex(item=>item.productName.toLowerCase() 
        === str.toLowerCase()),1)
           }
       }
      }
       sumPrice(str,num){
       var foundIndex = 
      products.findIndex(x=>x.productName.toLowerCase() === 
    str.toLowerCase());
       if(foundIndex>=0)
       {
           products[foundIndex].cost = products[foundIndex].cost + num;
       }
      }
     sumTotal() {
       var total = 0;
       for (var obj in products)
       {
           total+= obj.amount*obj.cost;
       }
       return total;
      }
      write() {
       var total = 0;
       for (var obj in products)
       {
           console.log('Item: '+obj.productName + ' | 
    Quantity:'+obj.amount+' | Price:'+obj.cost);
           total+= obj.amount*obj.cost;
       }
       console.log('$'+total);

      }
      }


                .buyProduct({ item: 'jameson', quantity: '1'})

                .buyProduct({ item: 'bud light', quantity: '3'})

                .buyProduct({ item: 'corona', quantity: '4'})

                .buyProduct({ item: 'beer', quantity: '1'})

                .sumPrice('tequila', 5.99)

                .deleteProduct('corona')

                .sumPrice('beer', 5.04)

                .sumTotal()

                .write

预期输出:

项目:jameson |数量:1 |价格:不适用

Item: jameson | Quantity: 1 | Price: n/a

项目:芽光|数量:3 |价格:不适用

Item: bud light | Quantity: 3 | Price: n/a

项目:电晕|数量:3 |价格:5.99美元

Item: corona | Quantity: 3 | Price: $5.99

项目:啤酒|数量:1 |价格:1.04美元

Item: beer | Quantity: 1 | Price: $1.04

总计:$ 19.01

Total: $19.01

推荐答案

执行诸如object.methodA().methodB()之类的东西会发生什么? .methodB在任何对象上被调用.methodA()返回.例如,以下代码将遇到与您相同的问题:

What happens when you execute something like object.methodA().methodB()? .methodB is called on whatever object.methodA() returns. For example, the following code will have the same problem you do:

const dog = {
    bark: function(){
        console.log('The dog barks at the mail man!')
    },
    chase: function(){
        console.log('The dog chases the mail man!')
    }
}

dog.bark().chase(); //Uncaught TypeError: Cannot read property 'chase' of undefined

我们可以通过以下操作解决此问题:

We can fix this by doing the following:

const dog = {
    bark: function(){
        console.log('The dog barks at the mail man!')
        return dog;
    },
    chase: function(){
        console.log('The dog chases the mail man!')
        return dog;
    }
}

dog.bark().chase(); // The dog barks at the mail man! The dog chases the mail man!

要修复代码,您将需要每种方法返回Product的实例.如cvgn所建议的那样,最简单的方法可能是返回this关键字,因为this对应于调用方法的对象:

To fix your code, you will need each method to return an instance of Product. The easiest way to do this is probably to return the this keyword, as cvgn suggests, since this corresponds to the object on which a method is called:

var products = [];
class Product {
   constructor() {

    }

    buyProduct(product){
       products.push(product);
       return this; // return object used in calling .buyProduct, `prod` in example below.
    }
}

const prod = new Product();

prod.buyProduct({ item: 'bud light', quantity: '3'})
    .buyProduct({ item: 'jameson', quantity: '1'});
console.log(products); 
//output will be an array of the product objects

为什么sumPrice方法可能会给您一个错误:

Explanation for why the sumPrice method is probably giving you an error:

尝试将以下日志添加到您的sumPrice方法中,并注意记录的内容:

Try adding the following logs to your sumPrice method, and notice what is logged:

console.log('STR: ', str);
console.log('NUM: ', num);
console.log('PRODUCT :', products[0]);
console.log('PRODUCT NAME: ', products[0].productName);
/* ... */
//STR:  jameson, NUM:  3, PRODUCT : {item: "jameson", quantity: "1"}, PRODUCT NAME:  undefined

您传递给.buyProduct的对象是{item: 'jameson', quantity: '1'};它没有"productName"属性,因此您无法访问它.请注意,您将对.cost遇到同样的问题,因为您的对象也没有"cost"属性:

The object you pass to .buyProduct is {item: 'jameson', quantity: '1'}; it does not have a "productName" property, so you can't access it. Note that you will have the same problem with .cost, as your object does not have a "cost" property either:

products[foundIndex].cost = products[foundIndex].cost + num;
//products[foundIndex].cost  -> undefined; undefined + num -> NaN

您可以在短期内解决此问题,方法是将.productName切换为.item,并在.buyProduct调用中声明一个费用支持:

You can fix this in the short term by switching .productName to .item, and by declaring a cost prop in the .buyProduct call:

   /* ... */
    sumPrice(str,num){
        var foundIndex = 
            products.findIndex(x=>x.item.toLowerCase() === 
                str.toLowerCase());
    /* ... */

const prod = new Product;
prod.buyProduct({ item: 'jameson', quantity: '1', cost: 0}).sumPrice('jameson', 3.99)
console.log(products);

但是,我怀疑您的根本问题是与JavaScript构造函数有些混淆,因为您并没有在代码中真正使用它.基本上,构造函数在您使用new关键字时运行:

However, I suspect your underlying problem is some confusion with JavaScript constructors, since you're not really using the one in your code. Basically, the constructor runs when you use the new keyword:

var products = [];
class Product {
   constructor(productName, amount, cost) {
       this.productName = productName,
        this.amount = amount,
        this.cost = cost
    }
}

const prod = new Product('jameson', 1, 3.99);

console.log(prod);
//Product {productName: "jameson", amount: 1, cost: 3.99}

但是,您的buyProduct方法在推送到products数组时不使用该对象;它只是使用您传入的任何对象作为参数.此外,要以现在的方式使用构造函数,您需要为每个项目(const jameson = new Product('jameson'...) const pepsi = new Product('pepsi'...)等)创建一个新的类实例.

Your buyProduct method, however, does not use that object when it pushes to the products array; it just uses whatever object you pass in as an argument. Further, to use the constructor the way you have it now, you would need to create a new class instance for each item (const jameson = new Product('jameson'...) const pepsi = new Product('pepsi'...) etc).

我的建议是阅读class关键字和工厂函数,因为它们似乎是造成您大多数困惑的根源.这是一篇很好的文章: https://medium. com/javascript-scene/javascript-factory-functions-with-es6-4d224591a8b1

My recommendation would be to read up on the class keyword and on factory functions, since they seem to be the source of most of your confusion. Here's a pretty good article on that: https://medium.com/javascript-scene/javascript-factory-functions-with-es6-4d224591a8b1

这篇关于我如何获得此代码以打印出此输出.我一直对.buyproduct不确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆