简体   繁体   English

Javascript数组不使用for循环变量

[英]Javascript array not using for loop variable

I have an array filled with strings that have the same name as Google Maps Polygon Objects I've created. 我有一个数组填充了与我创建的Google Maps Polygon Objects同名的字符串。 I'd like to iterate through the array to set a specific option. 我想迭代数组来设置一个特定的选项。 Here's the code: 这是代码:

for (var i = 0; i < statesPoly.length; i++) {
    google.maps.event.addListener(statesPoly[i], 'mouseover', function() {
        statesPoly[i].setOptions({ strokeWeight: '2' });
    });
}

When executed I get "Cannot call method 'setOptions' of undefined" as the script seems to be using statesPoly[i] literally. 执行时,我得到“无法调用方法'setOptions'的未定义”,因为脚本似乎是字面上使用statesPoly [i]。 When I replace statesPoly[i] with, for example, statesPoly[11], the script works as expected. 当我用statesPoly [11]替换statesPoly [i]时,脚本按预期工作。

The loop also works as expected when I try something like this: 当我尝试这样的事情时,循环也按预期工作:

for (var i = 0; i < statesPoly.length; i++) {
    alert(statesPoly[i].strokeColor);
}

What am I doing wrong? 我究竟做错了什么?

UPDATE: 更新:

Getting closer here. 靠近这里。 I believe the reason that using this works in some cases is because my function is expecting an object and I am giving it a string. 我相信在某些情况下使用this的原因是因为我的函数期望一个对象而我给它一个字符串。 Could this be the case? 可能是这种情况吗?

alert(statesPoly[0]);
        google.maps.event.addListener(sarawakPoly, 'mouseover', function() {
            $("#"+statesPoly[0]).addClass("highlight");
            sarawakPoly.setOptions({ strokeWeight: '2' });
            //infowindow.open(map,marker);
        });

The code above will alert with SarawakPoly, and using statesPoly[0] as a string in the ID works as expected. 上面的代码将使用SarawakPoly进行警报,并使用statesPoly [0]作为ID中的字符串按预期工作。 This 这个

 alert(statesPoly[0]);
        google.maps.event.addListener(statesPoly[0], 'mouseover', function() {
            $("#"+statesPoly[0]).addClass("highlight");
            statesPoly[0].setOptions({ strokeWeight: '2' });
            //infowindow.open(map,marker);
        });

Does not work because "Uncaught TypeError: Cannot read property 'mouseover' of undefined" 不起作用,因为“Uncaught TypeError:无法读取未定义的属性'mouseover'”

If I'm right, how to I get my JS to cast my array variable as an object? 如果我是对的,如何让我的JS将我的数组变量转换为对象?

This is a very common mistake in JavaScript code: 这是JavaScript代码中一个非常常见的错误:

for (var i = 0; i < n; i++) {
    registerSomeCallback(function () {
        console.log(i);
    });
}

On each loop iteration the variable i is incremented, and becasue of JavaScript's lexical scoping the functions defined on each iteration share the same i variable. 在每次循环迭代中,变量i递增,并且由于JavaScript的词法范围 ,每次迭代上定义的函数共享相同的i变量。 This means that when the callback is invoked (in your case when a Google Maps event occurs), i will always be the last value the loop reached. 这意味着当调用回调时(在您发生Google Maps事件的情况下), i将始终是循环达到的最后一个值。

It's as if you're doing this: 就好像你这样做:

var i, fn;

i = 0;
fn = function () { alert(i); };
fn(); // will alert "0"
i = 1;
fn(); // i has changed, will now alert "1"
i = 2;
fn(); // i has changed again, will now alert "2"

You need to make sure there's a new variable scope for each iteration of your loop, for example: 您需要确保循环的每次迭代都有一个新的变量范围,例如:

for (var i = 0; i < n; i++) {
    (function (n) {
        registerSomeCallback(function () {
            console.log(n);
        });
    }(i));
}

In this version of the code, each callback is defined in its own variable scope with its own counter variable (which you could still call i , but I've called n to make the example more clear). 在这个版本的代码中,每个回调都在它自己的变量作用域中定义,并带有自己的计数器变量(你仍然可以调用i ,但我调用了n来使示例更加清晰)。

Can you try using this instead? 你可以尝试使用this吗?

    for (var i = 0; i < statesPoly.length; i++) {
      (function(i) {
        google.maps.event.addListener(statesPoly[i], 'mouseover', function() {
            this.setOptions({ strokeWeight: '2' });
        });
       })(i);
    }

statesPoly[i] is undefined because your variable i is not defined inside the new function you attached to the event listener. statesPoly [i]未定义,因为您的变量i未在附加到事件侦听器的新函数内定义。

You can do several things here but the most simple way will be to pass this variable to the function. 你可以在这里做几件事,但最简单的方法是将这个变量传递给函数。 Something like that: 像这样的东西:

google.maps.event.addListener(statesPoly[i], 'mouseover', function(i) {
  statesPoly[i].setOptions({ strokeWeight: '2' });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM