[英]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.