vs forEach的JavaScript

时间:2017-07-11 21:14:53

标签: javascript loops for-loop foreach

my codeforEach我们可以得到当前值,在for的情况下,我们得到数组的最后一个值。按钮与数组中当前值之间的连接如何工作?

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>

1 个答案:

答案 0 :(得分:-1)

您正在获取数组的最后一个值,因为一旦该循环完成运行,i的值为2,并且在触发click事件时它仍然具有该值。 / p>