Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign value to an global array inside a function

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?

like image 559
gengchensh Avatar asked Dec 21 '25 07:12

gengchensh


1 Answers

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.

like image 169
Felix Kling Avatar answered Dec 23 '25 21:12

Felix Kling