Repeated data when traversing an array and displaying them in a list

1

I have the following code: (also available in Codepen )

const agregar=document.querySelector('#agregar')
const inputAgregar=document.querySelector('#inputAgregar') 
const listaUl=document.querySelector('#listaUl') 

var datosArray=[] 

agregar.addEventListener('click', function() {
  if (inputAgregar.value=='') {
    alert('Esta vacio') 
    inputAgregar.focus()
  } else {
    datosArray.push(inputAgregar.value) 
    inputAgregar.value='' 
    inputAgregar.focus() 
    mostrar(datosArray)
  }
}) 

function mostrar(datosArray) {
  for( i of datosArray) {
    var listaLi=document.createElement('li')
    listaUl.appendChild(listaLi) 
    listaLi.innerText=datosArray 
    console.log(datosArray)
  }
}
<input type="text" id="inputAgregar">
<p>
  <button id="agregar">Agregar</button>
</p>
<ul id="listaUl"></ul>

Why do I get repeated data when traversing an array and displaying them in a list in JavaScript?

    
asked by Juan Vargas 18.06.2017 в 20:40
source

1 answer

2

Your code has several details:

  • The first is that to avoid errors and good practices you should go ; at the end of each sentence.
  • The second detail is that your variables have the same name of id, many browsers use the id as a global variable, so in the end you may get an error when you want to create a constant with the same name.

  • Finally, your error is that you are going through the array and adding the entire array to each li instead of each element of the array and you are not cleaning the ul element to add all of them again. new each time the mostrar method is called.

const agregarVar = document.querySelector('#agregar');
const inputAgregarVar = document.querySelector('#inputAgregar');
const listaUlVar = document.querySelector('#listaUl');

var datosArray = [];


agregarVar.addEventListener('click', function() {
  if (inputAgregarVar.value == '') {
    alert('Esta vacio');
    inputAgregar.focus();
  } else {
    datosArray.push(inputAgregarVar.value)
    inputAgregarVar.value = '';
    inputAgregarVar.focus();

    mostrar(datosArray);


  }
});

function mostrar(datosArray) {
  listaUlVar.innerHTML = '';
  for (elemento of datosArray) {
    var listaLi = document.createElement('li');
    listaUlVar.appendChild(listaLi);
    listaLi.innerText = elemento;
    console.log(elemento);

  }




}
<input type="text" id="inputAgregar">
<p>
  <button id="agregar">Agregar</button>
</p>
<ul id="listaUl"></ul>
    
answered by 18.06.2017 / 21:08
source