i++ vs. ++i in a JavaScript for loop

前端 未结 4 852
情书的邮戳
情书的邮戳 2021-02-14 21:23

Because of JSLint, I almost always use i += 1 to increment a JavaScript for loop, but for quick and dirty scripts, I use i++ instead.
However, I se

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-14 21:57

    There is a difference, however not when used in a for loop.

    In an expression, i++ evaluates to the previous value of i, and then i is incremented. ++i increments first, and evaluates then.

    For this reason, some programmers prefer to write ++i in their for-loops — either because they're used to it, or because they feel it is "more right" somehow.

    edit: More probable is the solution Overv proposed: a relict from C.

提交回复
热议问题