English 中文(简体)
如何访问函数外的 Javascramp 变量值
原标题: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]);

显然这将会包含在脚本标记中, 但所有 im 得到的只是控制台上的一个错误, 上面写着 : “ Profile[0] 没有定义 。 ”

有谁知道我哪里错了吗?我似乎无法理解,在我把价值观从函数传递到函数或函数之外时,我所看到的其他解决方案至今都没有奏效。

感谢任何能帮我的人 这可能是我错过的简单事!

最佳回答

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

我怀疑的是,你忘了在使用前给配置文件加载器打电话。

良好做法是,如本页其他答复所示,以显而易见的方式宣布你的全球变量。

依赖副作用并不是好的做法。


用于显示正在发生的事情的注释代码, < 坚固> 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




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签