内部循环中的函数调用只进行最后一次迭代 [英] Function call inside loop taking only last iteration
本文介绍了内部循环中的函数调用只进行最后一次迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码如下所示:
if (ACTIVETICKETS.length > 0)
{
for (var m in ACTIVETICKETS)
{
if (ACTIVETICKETS.hasOwnProperty(m))
{
var marker = new L.Marker(new L.LatLng(ACTIVETICKETS[m].location.x, ACTIVETICKETS[m].location.y));
createHtmlForPopUp(m, function(data)
{
console.log(m);
marker.bindPopup( data ); // calling a function with callback
tile_layer.addLayer(marker);
});
}
} // for loop ends here
}
在执行此操作时,我只获得m的最后一次迭代。 ACTIVETICKETS数组的总长度是16.所以我只得到15次输入16次
While executing this, I am getting only the last iteration of m. Total length of ACTIVETICKETS array is 16. So I am getting only 15 entered 16 time
推荐答案
下面的代码应该可行,但是我在上面评论过,请阅读 关闭 ,以便您了解为什么。
The code below should work, but as I commented above, please read about closure so you know why.
if (ACTIVETICKETS.length > 0) {
for (var m in ACTIVETICKETS) {
(function(x) {
if (ACTIVETICKETS.hasOwnProperty(x)) {
var marker = new L.Marker(new L.LatLng(ACTIVETICKETS[x].location.x, ACTIVETICKETS[x].location.y));
createHtmlForPopUp(x, function(data){
console.log(x);
marker.bindPopup( data ); // calling a function with callback
tile_layer.addLayer(marker);
});
}
})(m);
} // for loop ends here
}
这篇关于内部循环中的函数调用只进行最后一次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文