简体   繁体   English

将值赋给函数内的全局数组

[英]assign value to an global array inside a function

I wrote a javascript like following: 我写了一个类似下面的javascript:

<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. 它在我的chrome中警告了undefined而不是a I tried to alert(i) , and it works very well. 我试图alert(i) ,它运作良好。

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 : namewindow对象的属性

Gets/sets the name of the window. 获取/设置窗口的名称。

Don't forget that global variables are properties of the global object ( window ) as well. 不要忘记全局变量也是全局对象( window )的属性。 Now, it seems Firefox lets you override this property, but Chrome does not. 现在,似乎Firefox允许您覆盖此属性,但Chrome不会。 Try in the Chrome console: 在Chrome控制台中试用:

> name = [];
[]
> typeof name
"string"

The output should be "object" . 输出应该"object"

Conclusion: Don't use a global variable called name . 结论:不要使用名为name的全局变量。 It works perfectly if you rename your variable. 如果重命名变量, 它可以完美地工作

You're alerting name[i] out of the function; 你正在警告名称[i]的功能; but i is already 1 because you've incremented it in function. 但我已经1了,因为你在功能上增加了它。

so alert(name[0]); 所以alert(name[0]);

http://jsfiddle.net/5G4Tx/2/ 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. 当javascript解释器解析您的脚本时,它会将所有变量移动到范围的顶部。 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. 我刚刚在Chrome中测试了这个答案,但它不起作用。 Felix's answer is good 菲利克斯的答案很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM