Javascript迭代器不起作用,但硬编码的数字将



我正在尝试使用谷歌地图api创建动态标记,并且在使用迭代的变量时遇到问题。

我已经提交了生成标记和地图的代码,因为它似乎工作得很好。这是生成信息窗口的代码。

这段代码产生错误'this_marker_info[$n]' [undefined]不是一个对象

for(var $n = 0; $n < business.length; $n++){
   google.maps.event.addListener(this_marker[$n], 'click', function() {
       this_marker_info[$n].open(map, this_marker[$n]);
   });      
}

for(var $n = 0; $n < business.length; $n++){
   google.maps.event.addListener(this_marker[$n], 'click', function() {
       this_marker_info[0].open(map, this_marker[0]);
   });      
}

我所做的只是将第二个示例中的"this_marker_info[$n]"行中的数字0交换$n。open(地图,this_marker [$ n]);"

如有任何帮助,不胜感激

这是典型的闭包问题。当this_marker_info[$n].open(map, this_marker[$n]);被执行时,你已经完成了循环,$n的值是business.length

解决方法是写一个闭包:

for(var $n = 0; $n < business.length; $n++){
    (function ($the_actual_n) {
        google.maps.event.addListener(this_marker[$the_actual_n], 'click', function() {
            this_marker_info[$the_actual_n].open(map, this_marker[$the_actual_n]);
        });
    }($n)); // <-- call this 'anonymous' function with $n
}

使用Array.forEach()是一个很好的整洁的方法来修复它:

business.forEach(function(item, $n) {
   google.maps.event.addListener(this_marker[$n], 'click', function() {
       this_marker_info[$n].open(map, this_marker[$n]);
   });      
}

这样,包含函数永远不会增加$n,所以它将可靠地保持它的原始值。

若要在较旧的浏览器中使用Array.forEach(),请参阅此

最新更新