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]
– Romulo Lessa
The
forEachwill 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 offorEachthat I inked.– Luiz Felipe