Home > front end >  I converted this forEach code to for loop and the code is not working
I converted this forEach code to for loop and the code is not working

Time:11-12

Clicking the red exit button removes the player from the forEach code, but not for loop.

You click the blue button, next you click the red exit button to remove the player.

How would I get the for loop code to work the same as the forEach code?

This code is working.

https://jsfiddle.net/n1t3kjdw/

  function removePlayerHandler(evt) {
    const el = evt.target;
    const container = el.closest(".container");
    const wrapper = container.querySelectorAll(".wrap");
    wrapper.forEach(function(wrapper) {
      if (wrapper.player) {
        return removePlayer(wrapper);
      }
    });
  }

What did I do wrong here? https://jsfiddle.net/rbwsL8hf/

Why is this code not working, what needs to be fixed?

  function removePlayerHandler(evt) {
const el = evt.target;
const container = el.closest(".container");
const wrappers = container.querySelectorAll(".wrap"); {
  for (let i = 0; i < wrappers[i].length; i  ) {
    if (wrappers[i].player) {
      return removePlayer(wrappers[i]);
    }
  }
}
}

CodePudding user response:

In your changed code you have made the iteration condition check for wrappers[i].length instead of what I believe was intended wrappers.length. Otherwise, you are for each iteration checking if i is smaller than the i-th wrapper's length which may or may not be defined.

  function removePlayerHandler(evt) {
const el = evt.target;
const container = el.closest(".container");
const wrappers = container.querySelectorAll(".wrap"); {
  for (let i = 0; i < wrappers[i].length; i  ) { // HERE
    if (wrappers[i].player) {
      return removePlayer(wrappers[i]);
    }
  }
}
}

CodePudding user response:

Complementing @Salim answer, there is also an extra bracket in your code, try this:

function removePlayerHandler(evt) {
   const el = evt.target;
   const container = el.closest(".container");
   const wrappers = container.querySelectorAll(".wrap");
     for (let i = 0; i < wrappers.length; i  ) {
       if (wrappers[i].player) {
         return removePlayer(wrappers[i]);
        }
     }
}
  • Related