-1

How can I stop this Javascript code from passing the last number of the iteration to the delete function?

<html>
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="lista"></div>
</body>
    <script type="application/javascript">
        var dados = ['vassoura','lixo','papel'];
        function deletar(elemento){
            console.log(elemento);
        }
        function listar(){
            var div = document.getElementById('lista');
            for(i in dados){
                campo = document.createElement("output");
                button = document.createElement("button");
                button.addEventListener("click",()=>{
                    deletar(dados[i]);
                });
                button.innerHTML="deletar";
                div.appendChild(campo);
                div.appendChild(button);
                console.log(i);
                campo.value = dados[i]+" ";
                console.log(dados[i]);
            }
        }
        listar();
    </script>

it is passing the last number corresponding to iteration because when I click on the button the iteration has already been made and finished

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    The question is really a dupe of https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – epascarello Oct 04 '17 at 14:18
  • Ops... sorry guys... – Wagner Santos Oct 06 '17 at 11:39
  • 1
    Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Lucas Sep 04 '18 at 16:07

2 Answers2

0

Looks like here is a common mistake with a variable scope.

Simplest way is to either use closure or replace for(i in dados) at least with for(let i in dados)

Vasyl Moskalov
  • 4,242
  • 3
  • 20
  • 28
0

First ,get the length of dados. and check when i = dados_length (last element) then skip that code which you want to skip.

isarojdahal
  • 994
  • 8
  • 12