为什么后置自增运算符 ($j++) 永远不会将 $j 从 0 改变?
我在增量运算符方面遇到了一个奇怪的问题。下面的代码应该输出什么?
$j = 0;
for ($i=0; $i<100; $i++)
{
$j = $j++;
}
echo $j;
它回显 0。为什么不是 100?
编辑:当我将 $j = $j++
更改为 $j = ++$j
时,它会回显 100。
I've encountered a strange problem with the increment operator. What should the code below output?
$j = 0;
for ($i=0; $i<100; $i++)
{
$j = $j++;
}
echo $j;
It echoes 0. Why not 100?
Edit: When I change $j = $j++
to $j = ++$j
, it echoes 100.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在执行“后增量”,因为
++
出现在它正在修改的变量之后。以不太紧凑的形式编写的代码可以归结为:如果您有
++$j
,则 j 将首先递增,并且所得递增值将分配回 J。但是,这样结构没有什么意义。你可以简单地写出归结为
You're doing a "post-increment", since the
++
appears AFTER the variable it's modifying. The code, written out in less compact form, boils down to:If you had
++$j
, then j would increment FIRST, and the resulting incremented value would be assigned back to J. However, such a structure makes very little sense. you can simply write outwhich boils down to
问题在于此
命令将
$j
计算为 0,然后将$j
递增到 1,最后将 0 赋值给$j< /代码>。
使用
$j = $j + 1;
或仅使用$j++;
。The problem is with the line
This command evaluates
$j
as 0, then increments$j
to 1, and finally does the assignment of 0 back to$j
.Either use
$j = $j + 1;
or just$j++;
.$j++
是后递增:表达式的值为$j
,然后$j
递增。因此,您将获取 j 的值,然后递增 j,然后将 j 设置为 j 的原始值。$j++
is post-increment: the value of the expression is$j
, then$j
is incremented. So you're getting the value of j, then incrementing j, then setting j to the original value of j.