I wrote a javascript like following:
<script language="javascript" type="text/javascript">
var name = new Array();
var i = 0;
function doSomething() {
name[i] = "a";
alert(name[i]);
i++;
}
</script>
It alerted an undefined instead of an a in my chrome. I tried to alert(i), and it works very well.
How can I assign values to a global array inside a function?
Problem solved: I just renamed the array and it worked! But why?
name is a property of the window object:
Gets/sets the name of the window.
Don't forget that global variables are properties of the global object (window) as well. Now, it seems Firefox lets you override this property, but Chrome does not. Try in the Chrome console:
> name = [];
[]
> typeof name
"string"
The output should be "object".
Conclusion: Don't use a global variable called name. It works perfectly if you rename your variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With