javascript类方法中的for循环不起作用

javascript类方法中的for循环不起作用,javascript,for-loop,Javascript,For Loop,在javascript中,我试图在类的函数中使用for循环。这是我的密码: <!DOCTYPE html> <html> <body> <p>Testing</p> <p id="thing"></p> <script> class test{ func(){ for (t=0; t<4; t++){ // If you comment out }

在javascript中,我试图在类的函数中使用for循环。这是我的密码:

<!DOCTYPE html>
<html>
<body>

<p>Testing</p>

<p id="thing"></p>


<script>

class test{

  func(){
    for (t=0; t<4; t++){         // If you comment out
    }                            // These lines it works
  }
}

var x = new test();
x.func();
var str1 = "It works!";

document.getElementById("thing").innerHTML = str1;
</script>

</body>
</html>
但如果我注释掉for循环,它会给出以下输出:

Testing
Testing
It works!
我以前在函数中使用过for循环,为什么我不能/如何在类函数中使用它们


谢谢

您的代码不起作用,因为变量
t
未声明。。 您试图在类范围内声明一个全局变量,这是不可能/无效的

只需将变量声明为范围变量(
var t=0
),它就可以工作了

func() {
  for (var t = 0; t < 4; t++) {}
}
func(){
对于(var t=0;t<4;t++){
}

打开浏览器的开发者控制台,你会发现原因。同意@squint,开发者应该学会使用他的工具(控制台、ide、linting)