2012-05-23 97 views
1

我一直在用砖头墙把我的头撞到墙上,而这一幕又一次都没有成功。我想要做的是访问函数内的数组中设置的值,但不在该函数内。这怎么能做到?例如:如何访问功能之外的Javascript变量值

function profileloader() 
{ 
    profile = []; 
    profile[0] = "Joe"; 
    profile[1] = "Bloggs"; 
    profile[2] = "images/joeb/pic.jpg"; 
    profile[3] = "Web Site Manager"; 
} 

我会再往一个段落标记中的页面有类似:

document.write("Firstname is: " + profile[0]); 

显然,这将在脚本标签包含有但所有我得到的是控制台上出现错误:“配置文件[0]未定义”。

任何人有任何想法,我哪里会出错?我似乎无法解决这个问题,并且在将函数的值传递给函数或函数之外时,我所见过的其他解决方案都无法实现。

谢谢任何​​能够帮助我的人,它可能是我错过的简单东西!

回答

4

既然你没有在profile=[];的前面有var,它存储在全局窗口范围内。

我怀疑是在使用它之前忘记调用profileloader()。

这是很好的做法是在一个明显的方式来声明全局变量,如在其他的答案本页面

它不被认为是很好的做法,依靠副作用上。


注释掉的代码显示是怎么回事,注意不推荐的方法:

这应该工作。它确实有效:DEMO

function profileloader() 
{ 
    profile = []; // no "var" makes this global in scope 
    profile[0] = "Joe"; 
    profile[1] = "Bloggs"; 
    profile[2] = "images/joeb/pic.jpg"; 
    profile[3] = "Web Site Manager"; 
} 
profileloader(); // mandatory 
document.write("Firstname is: " + profile[0]); 
+0

请不要推荐未声明的变量,更好的是将它们声明在要使用的范围中,然后分配给它们。 – RobG

+1

我在哪里推荐未申报的增值税? – mplungjan

+2

那么,你不建议宣布他们,* ipso * * facto *你建议不宣布他们。 :-) – RobG

3

声明它的函数外部,外面的范围可以看到它(注意全局的虽然)

var profile = []; 
function profileloader(){ 
    profile[0] = "Joe"; 
    profile[1] = "Bloggs"; 
    profile[2] = "images/joeb/pic.jpg"; 
    profile[3] = "Web Site Manager"; 
} 

或有函数返回它:

function profileloader(){ 
    var profile = []; 
    profile[0] = "Joe"; 
    profile[1] = "Bloggs"; 
    profile[2] = "images/joeb/pic.jpg"; 
    profile[3] = "Web Site Manager"; 
    return profile; 
} 

var myprofile = profileloader(); //myprofile === profile 
+1

好的假设,但不正确。 var的缺乏使得它成为一个全局变量。 – mplungjan

+0

@ mplungjan - 关于它没有任何“不正确的”。将它明确地声明为全局更好,因此很明显,范围旨在对可能维护代码的其他人是全局而非偶然的。 – RobG

+1

我的意思是,OP的问题是由于未申报的变量导致的错误。对不起,如果不明确。如果重新阅读我不回答使用本地声明的全局变量的答案,你会明白我的意思。 – mplungjan