Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript array not using for loop variable
    text
    copied!<p>I have an array filled with strings that have the same name as Google Maps Polygon Objects I've created. I'd like to iterate through the array to set a specific option. Here's the code:</p> <pre><code>for (var i = 0; i &lt; statesPoly.length; i++) { google.maps.event.addListener(statesPoly[i], 'mouseover', function() { statesPoly[i].setOptions({ strokeWeight: '2' }); }); } </code></pre> <p>When executed I get "Cannot call method 'setOptions' of undefined" as the script seems to be using statesPoly[i] literally. When I replace statesPoly[i] with, for example, statesPoly[11], the script works as expected. </p> <p>The loop also works as expected when I try something like this:</p> <pre><code>for (var i = 0; i &lt; statesPoly.length; i++) { alert(statesPoly[i].strokeColor); } </code></pre> <p>What am I doing wrong?</p> <p>UPDATE:</p> <p>Getting closer here. I believe the reason that using <code>this</code> works in some cases is because my function is expecting an object and I am giving it a string. Could this be the case? </p> <pre><code>alert(statesPoly[0]); google.maps.event.addListener(sarawakPoly, 'mouseover', function() { $("#"+statesPoly[0]).addClass("highlight"); sarawakPoly.setOptions({ strokeWeight: '2' }); //infowindow.open(map,marker); }); </code></pre> <p>The code above will alert with SarawakPoly, and using statesPoly[0] as a string in the ID works as expected. This</p> <pre><code> alert(statesPoly[0]); google.maps.event.addListener(statesPoly[0], 'mouseover', function() { $("#"+statesPoly[0]).addClass("highlight"); statesPoly[0].setOptions({ strokeWeight: '2' }); //infowindow.open(map,marker); }); </code></pre> <p>Does not work because "Uncaught TypeError: Cannot read property 'mouseover' of undefined"</p> <p>If I'm right, how to I get my JS to cast my array variable as an object? </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload