最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - assign value to an global array inside a function - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Apr 7, 2011 at 7:48 gengchensh asked Apr 7, 2011 at 7:29 gengchenshgengchensh 632 silver badges7 bronze badges 1
  • @Headshota someting is fishy jsfiddle/5G4Tx – S L Commented Apr 7, 2011 at 7:36
Add a ment  | 

3 Answers 3

Reset to default 5

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/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)

  1. 暂无评论