gpt4 book ai didi

javascript - 在 while 循环定义中使用 var 关键字

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:05:06 25 4
gpt4 key购买 nike

在 JavaScript 的 for 循环中,我可以在类似这样的循环定义中使用 var 关键字:

for (var i=0; i<10; i++) ...

我知道变量 i 的范围不在循环内,而是在声明循环的函数内。这是比在循环外声明局部变量 i 更好的表示法(最糟糕的表示法是在函数体的开头声明 i 变量):

var i;
for (i=0; i<10; i++) ...

我的问题是关于 while 循环。我不能像这样在 while 循环定义中声明变量:

while((var match = re.exec(pattern)) != null) ...

我必须在 while 循环之外使用 var 关键字。

var match;
while((match = re.exec(pattern)) != null) ...

我做错了什么吗?

最佳答案

Am I doing something wrong?

不,你不是。这就是语法的定义方式。 while 循环只接受表达式,而 for 循环也可以与 var 声明一起使用。

参见 https://es5.github.io/#x12.6 :

while ( Expression ) Statement
for ( ExpressionNoIn_opt; Expression_opt ; Expression_opt ) Statement
for ( var VariableDeclarationListNoIn; Expression_opt ; Expression_opt ) Statement

关于javascript - 在 while 循环定义中使用 var 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25233782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com