Can someone explain this JavaScript mystery? -
i writing simple recursive function in javascript , encountered weird behavior. @ first thought it's bug in browser, tried in firefox, chrome , ie9 , behave same way.
the html file below runs simple js function on page load. function recursive (calling once). function creates new array object , returns it. weird thing after function calls recursively, x , y reference same object, far understand should not happen. if uncomment last line before return x, alert "x == y" alert not shown.
<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>javascript weirdness...</title> <script type="text/javascript" language="javascript"> function recursivef(n) { x = [ n ]; if (n > 0) { y = recursivef(n - 1); if (x == y) alert('x == y'); } //if (n == 0) return [ n ]; return x; } </script> </head><body onload="javascript:recursivef(1);"></body></html>
any hints why "x == y" alert appears in page?
x
, y
default global variables shared recursive calls of function. if want them local, declare them var
keyword.
Comments
Post a Comment