if 和 while 语句条件部分的赋值

Assignments in the condition part of if and while statements

这里引用 Crockford:

Assignment Expressions

Avoid doing assignments in the condition part of if and while statements.

Is

if (a = b) {

a correct statement? Or was

if (a == b) {

intended? Avoid constructs that cannot easily be determined to be correct.

// Here is an assignment as I understand it:
var var1 = "foo";
var var2 = "bar";

// And what is shown in Crockford's quote isn't an assignment.

那么,Crockford 的话是什么意思?

表示

if (a = b) {

实际上是一个赋值,将b的值赋值给a,这通常不是一个人想要的。

那段话只是告诉你要当心,只有当你真心实意时才这样做,而你通常不会这样做。一般都想在那里做个对比,所以

if (a == b) {

反例:如果你运行下面的,它只会打印true只有当你对确认弹出窗口给出OK时,才会打印

if(a = confirm('test')) { console.log(a) }

注意有一个赋值,我们正在 if.

中打印 a 的值
   var username = prompt("username");
   var password = prompt("password");

   if(username = "youdontknowme") 
     if(password = "12345678")
        alert("logged in successfully!");

好像对吧?就试一试吧!因此,大多数 IDE 会警告您赋值可能应该是比较。如果你没有这样的杠杆 IDE,你需要自己发现它,这就是为什么克罗克福德先生试图让你意识到它。