array only displays the first length using foreach

Asked

Viewed 32 times

-2

I am wanting to display an array within a list but when I run the function only displays the first number of the array

let lista = document.getElementById("lista");
  par.forEach(()=>{
    let item = document.createElement("li");
    for(i = 0; i < par.length; i++){
      item.appendChild(document.createTextNode(par[i]));
      return lista.appendChild(item)
    }
  });

In HTML comes out like this

2
2
2
2

on the console

par
(4) [2, 4, 6, 8]

1 answer

4


There is a serious problem of understanding in your code, as you are nesting unnecessarily, a for within a forEach.

The forEach will invoke the callback passed to each member of the array, which will cause your for be it servant four times, always with the zero index.

You should use one or the other. With the for:

const lista = document.getElementById('lista');
const par = [2, 4, 6, 8];

for (let i = 0; i < par.length; i++) {
  const item = document.createElement('li');
  item.appendChild(document.createTextNode(par[i]));
  lista.appendChild(item);
}
<ul id="lista"></ul>

If you want to use the for and the environment support, can also choose to for..of.

Or with a forEach:

const lista = document.getElementById('lista');
const par = [2, 4, 6, 8];

par.forEach((elemento) => {
  const item = document.createElement('li');
  item.appendChild(document.createTextNode(elemento));
  lista.appendChild(item);
});
<ul id="lista"></ul>

  • It takes me a doubt about the foreach. I did not understand right the part that he understands that the element will be the length of the pair, when putting the (element) it automatically understands that I’m talking about the pair[length]

  • The forEach will invoke the callback that you passed it to each iteration, passing the elements and other data as parameter. Thus, within the callback, you can access the parameters corresponding to the element and index of the current iteration, as well as the array (in order of parameter 1, 2 and 3). To learn more, see documentation of forEach that I inked.

Browser other questions tagged

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