无法在函数中检索全局变量的值

Cannot retrieve global variable's value inside function?

本文关键字:全局变量 检索 函数      更新时间:2023-09-26

>由于在函数内返回变量,我一直得到"未定义"。

这是代码:

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

它有什么问题?/什么可能导致问题?

请检查此代码图片。

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