2012-08-16 34 views
-1

我一直收到「未定義」作爲返回函數內的變量的結果。無法檢索函數內的全局變量值?

這是代碼:

var nloads = 1; 
function something(loc) { 
    console.log(nloads); // returns 1 
} 
function changeSection(loc) { 
    console.log(nloads); // Returns undefined 
    nloads = nloads + 1; 
    temp = nloads; 
} 

什麼地方錯了/什麼可導致此問題?

+2

你在哪裏調用這些函數? – MichaelS 2012-08-16 05:57:29

回答

0

請檢查這張圖片的代碼。

<html> 
<head> 
</head> 
<body> 
<script> 
var nloads = 1; 
function something(loc) { 

    alert(nloads); // returns 1 
} 
function changeSection(loc) { 
    alert(nloads); // Also returns 1 
    nloads = nloads + 1; 
    temp = nloads; 
} 


</script> 
<div style="border:solid red; height: 100px;width: 100px;" onClick="something('f');changeSection('f');"> 
</div> 

</body> 
</html> 
-1
var nloads = 1; 
function something(loc) { 
    console.log(nloads); // returns 1 
} 
function changeSection(loc) { 
    nloads = nloads + 1; 
    **var** temp = nloads; // I was missing var before declaring the variable 
    console.log(nloads); 
}