Uncaught Typeerror: Cannot read Property 'num' of Undefined at Htmlanchorelement.addItem

Asked

Viewed 72 times

0

I started doing the program in JS to have interaction with the front and I got this error. When it is to show the product, it works by showing the product name on the console, but beats this error, I would like to know how to fix

const select = document.querySelectorAll("[data-ordem]");
const shopProduct = [
 {
    num: 0,
    name: 'Bebedouro',
    price: 20
  },
  {
    num: 1,
    name: 'Massageador para gatos',
    price: 15
  },
  {
    num: 2,
    name:'Kit Spray com brinquedo de catnip',
    price: 40
  },
  {
    num: 3,
    name:'Sache de Catnip',
    price: 5
  }
];

select.forEach((e) => {
  let newItem = parseInt(e.dataset.ordem);
  e.addEventListener('click', addItem);
    function addItem(e){
      e.preventDefault();
        for(i=0; i <= shopProduct.length; i++){
          if(newItem === shopProduct[i].num){
            console.log(shopProduct[i].name);
          }
        }
    }
})

1 answer

0


The estate length of an array returns its size. However, its indexing always starts at position 0, which means an array whose length be 3 has indices 0, 1 and 2.

Thus, the error happens because you are trying to access index 4 of an array that has indexes 0, 1, 2 and 3. The cause is in the cycle stop condition for.

Try changing:

for(i=0; i <= shopProduct.length; i++){

To:

for(i=0; i < shopProduct.length; i++){
  • I hadn’t thought that way about for, gave me a new way of thinking and still solved my bug, thank you very much.

  • Great. If the answer was helpful, mark it as correct ;-)

  • Done. I’m still learning how to use the platform

Browser other questions tagged

You are not signed in. Login or sign up in order to post.