javascript中while变量的声明 [英] declaration for variable in while condition in javascript

查看:84
本文介绍了javascript中while变量的声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本质上,我试图在javascript中的while循环的条件部分声明一个变量:

In essence, I am trying to declare a variable in the condition-part of a while loop in javascript:

while (var b=a.pop()) {
  do_sth(b)
}

然而,我的浏览器(firefox)不接受这一点。相反,我必须这样:

Yet, my browser (firefox) doesn't accept that. Instead I have to go like so:

var b
while (b=a.pop()) {
  do_sth(b)
}

有效。预期会出现这种情况吗?

which works. Is this behaviour expected?

推荐答案

这个问题有点陈旧,但我认为答案都错过了一个重要的区别。也就是说,循环需要一个表达式,它会被调整为一个条件,即一个可以转换为布尔值的布尔值或值。有关详细信息,请参阅 Mozilla文档

The question is a little dated, but I think the answers all miss an important distinction. That is, a while loop expects an expression that evaulates to a conditional, i.e., a boolean or value that can be converted to a boolean. See Mozilla docs for details.

纯粹的赋值(没有实例化)通过其默认返回值(右侧的值)强制转换为布尔值。

A pure assignment (without instantiation) is coerced to a boolean via its default return value (the value of the right-hand-side).

A var (或 const )是一个语句,它允许一个可选的赋值,但其返回值为 undefined

A var (or let or const) is a statement that allows an optional assignment but has a return value of undefined.

您可以在控制台中轻松测试:

You can easily test this in your console:

var foo = 42; // undefined
bar = 42      // 42

单独的返回值无法回答问题,因为 undefined 是假的,但确实表明即使JS允许你在条件中放入 var 只会总是评估为false。

The return values alone don't answer the question, since undefined is falsey, but does show that even if JS let you put a var in a conditional it would simply always evaluate to false.

其他人已经提到语句,并且它们允许变量的声明和实例化。这是事实,但文档解释 需要一份陈述或分配。

Others have mentioned for statements and that they allow declaration and instantiation of variables. This is true, but the documentation explains that for expects a statement or assigment.

意见可能会有所不同,但对我而言,所有这些都增加了可理解的一致性关于循环的行为不是怪癖。一个循环更好地被认为是 if 语句的循环版本而不是 > for 循环。如果所有这些都有奇怪之处,则语句的与语言的正常语法大不相同。

Opinions may vary, but for me all this adds up to an understandable consistency not a quirk in behavior with regard to loops. A while loop is better thought of as a looping version of an if statement than akin to a for loop. If there is quirkiness in all of this, it's the for statement's wholesale divergence from the language's normal syntax.

这篇关于javascript中while变量的声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆