-1

In my code in the case of forEach we can get the current value, in the case of for we get the last value of the array. How does the connection between a button and the current value in the array work?

var arr = [{ name: "Model S" },
{ name: "Model X" }, { name: "Model 3" }];
var brElt = document.createElement("br");
arr.forEach(function (el) {
    var btnElt = document.createElement("button");
    btnElt.textContent = "Ok";
    btnElt.addEventListener("click", function (e) {
        e.target.textContent = el.name;
        e.target.style.color = "blue";

    })
    document.getElementById("contenu").appendChild(btnElt);
    document.getElementById("contenu").appendChild(brElt);
});

for (var i in arr) {
    var btnElt = document.createElement("button");
    btnElt.textContent = "Ok";
    btnElt.addEventListener("click", function (e) {
        e.target.textContent = arr[i].name;
        e.target.style.color = "green";

    })
    document.getElementById("contenu").appendChild(btnElt);
    document.getElementById("contenu").appendChild(brElt);
};
<div id="contenu"></div>
4castle
  • 32,613
  • 11
  • 69
  • 106
  • Your question is like comparing while and for. – Arthur Guiot Jul 11 '17 at 21:18
  • There's no code in your question. – Praveen Kumar Purushothaman Jul 11 '17 at 21:18
  • 1
    [Don't use `for…in` enumerations on arrays](https://stackoverflow.com/q/500504/1048572) anyway! – Bergi Jul 11 '17 at 21:22
  • @ArthurGuiot `forEach` creates a closure, but `for` does not. They aren't always interchangeable (as this question demonstrates). – 4castle Jul 11 '17 at 21:24
  • Bind the index argument so that it's copied! btnElt.addEventListener("click", function (index, e) { e.target.textContent = arr[index].name; e.target.style.color = "green"; }.bind(null, i)) – lovelikelando Jul 11 '17 at 21:24
  • The connection between button and array value is via the `el` and `i` variables, and their scope widely differs between `for (var …)` and `forEach` – Bergi Jul 11 '17 at 21:25
  • @4castle No, that’s not what I wanted to say. I’m simply saying that these functions are pretty different. The comparison with while is not an answer to the question, but simply a way of saying that they are different – Arthur Guiot Jul 12 '17 at 07:17

1 Answers1

-1

You're getting the last value of the array because i has a value of 2 as soon as that loop finishes running, and it still has that value when the click event is triggered.

anbnyc
  • 911
  • 6
  • 13