繁体   English   中英

如何在函数外部访问Javascript变量值

[英]How to access Javascript variable values outside of the function

我一直在用这个和另一个通宵达旦的砖墙砸头,但没有成功。 我想做的是可以访问在函数内部但在函数外部的数组中设置的值。 怎么办呢? 例如:

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]);

显然,这将包含在script标记中,但是我得到的只是控制台上的一个错误,指出:“未定义profile [0]”。

有人知道我要怎么做吗? 我似乎似乎无法弄清楚,并且从一个函数到另一个函数或在一个函数外部传递值时,我所见过的其他解决方案都没有奏效。

谢谢任何可以帮助我的人,这可能是我想念的简单事情!

由于您在profile=[];前面没有var profile=[]; ,它存储在全局窗口范围内。

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

优良作法是以明显的方式声明全局变量,如本页其他答案所示

依靠副作用被认为不是好习惯。


用注释的代码显示正在发生的事情,不建议使用NOTE方法:

这应该工作。 它确实起作用: 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]);

在函数外部声明它,以便外部范围可以看到它(不过要注意全局变量)

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

暂无
暂无

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

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