JavaScript:如何修复未捕获的参考错误?

问题描述 投票:0回答:4

我已经了解到,每当我们不定义变量并仅在函数中初始化它时,它就被视为全局变量。我还了解到变量总是在程序开始运行时首先定义。

var globalVariable = "This is a global variable";

function fun(){
localVariable = "This is a local Varible";
console.log();
console.log();

}

console.log(localVariable);//This is a local Varible(Ouput)
console.log(globalVariable);//This is a global variable(Output)

上面的代码似乎工作正常,但我看到以下代码的输出很困惑,我试图清除我的概念。

var globalVariable = "This is a global variable"
function fun(){
console.log(localVariable); //Uncaught ReferenceError: localVariable is not defined

localVariable = "This is a local Varible";

}
fun();

console.log(globalVariable);//This is a global variable(Output)

我不确定为什么console.log(local Variable);给出了未捕获的参考错误

javascript
4个回答
1
投票

其他人对你的变量范围所说的是正确的,但我想补充一点。

“我已经知道变量总是在程序开始运行时首先定义。”

我认为这可能会让你感到困惑,JavaScript使用吊装。解析器读取整个函数并执行任何变量声明,就像在作用域的开头一样。但是你必须使用var关键字来声明它,目前你只是为它赋值。

例如,这可以起作用,尽管声明是在使用变量之后

x = 5; 
elem = document.getElementById("demo"); 
elem.innerHTML = x;                    
var x;

1
投票

尝试下面的代码工作 - 注意函数内部的var

var globalVariable = "This is a global variable"

function fun() {

  var localVariable = "NOW this is a local Variable";

  console.log(localVariable); //now this is a local variable

}
fun(); 

console.log(globalVariable); //This is a global variable(Output)

0
投票

首先,函数中定义的变量不是全局的,它们是本地的。

我认为你可能在定义之前调用局部变量。首先定义它,然后执行console.log()。


0
投票

很简单,为了查看任何变量的日志,您需要先定义它。

var globalVariable = "This is a global variable"
function fun(){

var localVariable = "This is a local Varible";
console.log(localVariable); //Uncaught ReferenceError: localVariable is not defined

}
fun();

console.log(globalVariable);//This is a global variable(Output)

JavaScript变量是用于存储数据值的容器。必须使用唯一名称标识所有JavaScript变量。这些唯一名称称为标识符。首先,您需要告诉哪个标识符代表什么,然后才能查看结果。

© www.soinside.com 2019 - 2024. All rights reserved.