有没有理由不在 while 块声明中分配变量

Is there a reason to not assign a variable in the while block declaration?

本文关键字:声明 分配 变量 while 有理由      更新时间:2023-09-26

每当我做这样的事情时...

var obj;
while (obj = doSomething()) {
  // something with obj
}

JSHint告诉我warning 84| Expected a conditional expression and instead saw an assignment..但是,执行obj = doSomething()会返回doSomething()在赋值期间返回的值,因此以这种方式编写 while 循环是有意义的。

JSHint警告我是否有特定的原因,更重要的是,有理由不这样做吗?或者我可以告诉 JSHint 忽略该特定警告的这些行吗?

该警告是为了确保您没有错误键入=而不是=====

相反,您可以获取评估结果的布尔值,如下所示

while (!!(obj = doSomething())) {

单个=分配值,而不是比较运算符。使用以下命令:

while (obj == doSomething()) {
  // something with obj
}

参考: http://www.w3schools.com/js/js_comparisons.asp