如何在函数外部访问Javascript变量值 [英] How to access Javascript variable values outside of the function

查看:49
本文介绍了如何在函数外部访问Javascript变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在和这个彻夜难眠的家伙一头撞在砖墙上,但没有成功.我想做的是可以访问在函数内部但在函数外部的数组中设置的值.怎么办呢?例如:

I've been banging my head off a brick wall with this one and another all nighter with no success. What I would like to do is have access to the values set in an array within a function but outside of that function. How could this be done? For example:

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

然后我将在段落标签内的页面下方进一步添加以下内容:

I would then further down the page within a paragraph tag have something like:

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

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

Obviously that would be contained with in the script tag but all i'm getting is an error on the console stating: "profile[0] is not defined".

有人知道我要怎么做吗?我只是似乎无法弄清楚,到目前为止,从一个函数到另一个函数或在一个函数之外传递值时,我所见过的其他解决方案都没有奏效.

Anyone got any ideas where I'm going wrong? I just can't seem to figure it out and none of the other solutions I've seen when passing values from either function to function or outside of a function, have worked so far.

感谢任何可以帮助我解决这个问题的人,这可能是我想念的简单事情!

Thank you to anyone who can help me with this, its probably something simple I've missed!

推荐答案

由于在profile=[];前面没有var,因此它存储在全局窗口范围中.

Since you do NOT have a var in front of the profile=[];, it is stored in the global window scope.

我怀疑是您忘记了在使用profileloader()之前先调用它.

What I suspect is that you forgot to call the profileloader() before using it.

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

It is good practice is to declare your global variables in an obvious manner, as shown in other answers on this page

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

It is not considered good practice to rely on side effects.

注释代码以显示正在发生的事情,注意不推荐使用的方法:

Commented code to show what is going on, NOTE not recommended method:

这应该有效.它确实有效:演示

This should work. And it does work: 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]);

这篇关于如何在函数外部访问Javascript变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆