Geo*_*980 4 javascript arrays variables function
我一直在用这个一个又一个晚上把头撞到砖墙上,但没有成功。我想要做的是访问在函数内但在该函数外的数组中设置的值。这怎么可能?例如:
function profileloader()
{
profile = [];
profile[0] = "Joe";
profile[1] = "Bloggs";
profile[2] = "images/joeb/pic.jpg";
profile[3] = "Web Site Manager";
}
Run Code Online (Sandbox Code Playgroud)
然后,我会在段落标签中的页面下方有类似的内容:
document.write("Firstname is: " + profile[0]);
Run Code Online (Sandbox Code Playgroud)
显然,这将包含在脚本标记中,但我得到的只是控制台上的错误,指出:“未定义配置文件 [0]”。
有人知道我哪里出错了吗?我似乎无法弄清楚,到目前为止,我在从函数到函数或在函数外部传递值时所看到的其他解决方案都没有奏效。
感谢任何可以帮助我解决这个问题的人,这可能是我错过的一些简单的事情!
在函数之外声明它,以便外部范围可以看到它(但要小心全局变量)
var profile = [];
function profileloader(){
profile[0] = "Joe";
profile[1] = "Bloggs";
profile[2] = "images/joeb/pic.jpg";
profile[3] = "Web Site Manager";
}
Run Code Online (Sandbox Code Playgroud)
或者让函数返回它:
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
Run Code Online (Sandbox Code Playgroud)
由于var
前面没有profile=[];
,因此它存储在全局窗口范围内。
我怀疑您在使用之前忘记调用 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]);
Run Code Online (Sandbox Code Playgroud)