JavaScript – no automatic conversion to number

I was surprised when I wrote code to extract values from cookie and using it to set map center. Well it looks like in JS there is no automatic conversion from string to number.

Code looks like:

   if ( res = getCookie("rnsloc").match("(.*)-(.*)-(.*)") ) {
      map.setCenter( new GLatLng(res[1], res[2]), res[3] )
    } else
      map.setCenter( new GLatLng(52.2419, 21.01), 11);

getCookie returns cookie content as a string, so does regexp. Well it works, but not 100% as it was expected.

It sets map center as it should, but zoom level is set to zero, or in other words there is no zoom. After some experiments I have discovered, that res[3] value (string “12”) is not converted to number, so zoom is set as 0. Well so working code should be:

   if ( res = getCookie("rnsloc").match("(.*)-(.*)-(.*)") ) {
      map.setCenter( new GLatLng(res[1], res[2]), Number(res[3]) )
    } else
      map.setCenter( new GLatLng(52.2419, 21.01), 11);

Small difference of direct cast, but it make its day. However I don’t know why GLatLng accepts numeric strings as arguments, and setCenter does not…

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.