开发者

assign value to an global array inside a function

I wrote a javasc开发者_如何学运维ript 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.


You're alerting name[i] out of the function; but i is already 1 because you've incremented it in function.

so alert(name[0]);

http://jsfiddle.net/5G4Tx/2/


This may because of hoisting.
You might think that variables and functions are defined in the same order as they appear in your script but this is not true. Here is a good article on hoisting.
When the javascript interpreter parses your script it moves all the variables to the top of the scope. This happens with function declarations too. I think that what has happened in your case is that the function declaration has been hoisted above the variables and so they are not available within its scope. This behaviour might vary across browsers. You can fix it by using a function expression instead.

var name = new Array();
var i = 0;
var doSomething = function() {
    name[i] = "a";
    alert(name[i]);
    i++;
}      

doSomething(); // alerts 'a'

EDIT

I've just tested this answer in Chrome and it doesn't work. Felix's answer is good

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜