我有一个图书馆,需要一个按钮数组才能生成一个UI,此数组中的对象带有 Text 可以显示,而 callback 可以在按下按钮。对于此示例作为回调,我使用console.log来显示在数组填充期间随机生成的值:
var buttons = [];
for(var x = 0; x < 3; x++) {
var value = Math.random()*10;
buttons.push({
text: "Foo",
onTap: function() { console.log("Im a button and my value is", value) } })
}
您可以立即看到,因为 onTap 稍后在用户点击按钮时被调用,console.log显示的值是最后一个,这意味着所有按钮都将显示相同的值。我可以修改库以在对象中包含某种元字段,在其中可以存储值,然后从onTap函数中检索它们。但是我不想碰图书馆,有没有更好的方法来解决这个问题?
答案 0 :(得分:0)
for不受范围限制,因此value始终是最后一个值,您可以通过在下面的函数中变形
来限制范围的值
var buttons = [];
for(var x = 0; x < 3; x++) {
(function() {
var value = Math.random()*10;
buttons.push({
text: "Foo",
onTap: function() { console.log("Im a button and my value is", value) } })
})();
}
供参考:https://scotch.io/tutorials/understanding-scope-in-javascript
或者仅使用let代替var
var buttons = [];
for(var x = 0; x < 3; x++) {
let value = Math.random()*10;
buttons.push({
text: "Foo",
onTap: function() { console.log("Im a button and my value is", value) } })
}