admin管理员组文章数量:1387389
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
3 Answers
Reset to default 5name
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
本文标签: javascriptassign value to an global array inside a functionStack Overflow
版权声明:本文标题:javascript - assign value to an global array inside a function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744501877a2609367.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论