开发者

while(0=0) evaluates to false

b=10;
while(a=b) {
  b--;
  if(b==-10)break;
}

B goes from 10 to -10. In my world, the while-statement, a=b, should always be true (since the assigment always "goes well"). That is no开发者_如何学Ct the case. When the loop stops, b will have a value of 0.

In my world, it should pass 0 and go all the way to -10, when the if-statement kicks in.

Have I misunderstood something major? (Code tested in IE8 and Adobe Acrobat)


(0 = 0) == 0 == false


The value of an assignment is the value being assigned, so you can chain assignments a = b = 2 for example, so when b=0, the value of a=b is 0.


0 is a falsey value, 0 == false is true, so as soon as b hits 0, then a = b evaluates to false and the loop breaks.

A simple fix would be

while ((a=b) > -10) {

or in this case, due to the break; statement you could just use

while (true) {


Yes, because the value of the assignment is that value that of the expression that is assigned. Which is 0, which is evaluated to false.


Obviously, if(0) is equivalent to if(false).

So, if(a=b) is true only if b equals to something that would become true if cast to boolean.

So, if say a and b are same type, it will be considered true if b is non-zero.

What I don't understand is why this code?


0 is falsy in javascript, a=b returns 0 when b reaches 0, thus javascript reads false.


the while-statement, a=b, should always be true (since the assignment always "goes well").

It's generally not a good idea to think of the return value as confirmation of the success of the operation. The continued execution of your code is the indication that the assignment went well.

Notably, your intuition is actually backwards from the standard in Unix shell scripting, where 0 means A-OK! and non-zero indicates some other result.

Now that things like Exceptions can be used to indicate a problem in execution, there are better mechanisms to use for this.


While loop expects a condition i.e. while(condition) and deals with true or false Therefore, your loop above translates to while(a) ergo the condition for the loop is the value of a.

When a reaches 0, your loop breaks.


In fact 0 = 0 will give you a result of 0 which is interpreted as false. In other words while(0=0) is pretty much the same as while(0) which breaks the loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜