问题描述
这里是我想要运行的一个简化版本:
Here is a simplified version of something I'm trying to run:
for (var i = 0; i < results.length; i++) {
marker = results[i];
google.maps.event.addListener(marker, 'click', function() {
change_selection(i);
});
}
但我发现每个监听器使用results.length当for循环终止时的值)。如何添加侦听器,使得每个在使用i的值时添加它,而不是对i的引用?
but I'm finding that every listener uses the value of results.length (the value when the for loop terminates). How can I add listeners such that each uses the value of i at the time I add it, rather than the reference to i?
推荐答案
您需要创建一个单独的作用域,通过将变量作为函数参数传递将其保存为当前状态: p>
You need to create a separate scope that saves the variable in its current state by passing it as a function parameter:
for (var i = 0; i < results.length; i++) {
(function (i) {
marker = results[i];
google.maps.event.addListener(marker, 'click', function() {
change_selection(i);
});
})(i);
}
通过创建一个匿名函数并使用变量作为第一个参数调用它,你将传递给函数并创建一个闭包。
By creating an anonymous function and calling it with the variable as the first argument, you're passing-by-value to the function and creating a closure.
这篇关于如何将JS变量的值(而不是引用)传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!