为什么后置自增运算符 ($j++) 永远不会将 $j 从 0 改变?

发布于 2025-01-07 12:08:01 字数 237 浏览 4 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

合久必婚 2025-01-14 12:08:01

您正在执行“后增量”,因为 ++ 出现在它正在修改的变量之后。以不太紧凑的形式编写的代码可以归结为:

for ($i = 0; $i < 100; $i++) {
   $temp = $j;  // store j
   $j = $j + 1;  // $j++
   $j = $temp; // pull original j out of storage
}

如果您有 ++$j,则 j 将首先递增,并且所得递增值将分配回 J。但是,这样结构没有什么意义。你可以简单地写出

 for (...) {
    $j++;
 }

归结为

for (...) {
   $j = $j + 1;
}

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:

for ($i = 0; $i < 100; $i++) {
   $temp = $j;  // store j
   $j = $j + 1;  // $j++
   $j = $temp; // pull original j out of storage
}

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 out

 for (...) {
    $j++;
 }

which boils down to

for (...) {
   $j = $j + 1;
}
○愚か者の日 2025-01-14 12:08:01

问题在于此

$j = $j++;

命令将 $j 计算为 0,然后将 $j 递增到 1,最后将 0 赋值给 $j< /代码>。

使用 $j = $j + 1; 或仅使用 $j++;

The problem is with the line

$j = $j++;

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++;.

匿名的好友 2025-01-14 12:08:01

$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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文