i--和i = i-1的评估不一样 [英] i-- and i = i-1 not evaluating the same

查看:142
本文介绍了i--和i = i-1的评估不一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为i--i = i - 1的简写,但是我发现两者的评价不同:

I thought that i-- is a shorthand for i = i - 1, but I discovered that both evaluate different:

var i = 1;
while (i = i - 1) {…}

在这种情况下,i0,其值为false.这按预期工作.

In this case, i is 0, which evaluates to false. This works as expected.

var i = 1;
while (i--) {…}

i应该为0并求值为false,但不是.计算结果为true.这是错误,还是有原因?

i should be 0 and evaluate to false, but it does not. It evaluates to true. Is this a bug, or is there a reason for it?

推荐答案

仅在评估循环条件之后,但在循环语句之前之前,评估i--.这是减量后缀运算符.这意味着,最初在循环条件中对条件的评估为true.这将触发循环主体中语句的执行.当执行循环主体中的语句时,由于i已减1,因此它等于0.因此,循环条件的评估结果为false,而循环主体中的语句将不再次执行.

The i-- will be evaluated only after the loop condition is evaluated but before the statements within the loop. This is the decrement postfix operator. That means that initially the evaluation of the condition in the loop condition would be true. This will fire the execution of the statements in the loop's body. When the statements in the loop's body will be executed, since the i had be decremented by one, it would be equal to 0. Hence the evaluation of the loop condition would be false and the statements in the loop's body will not be executed again.

这篇关于i--和i = i-1的评估不一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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