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

前端 未结 4 847
情书的邮戳
情书的邮戳 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:50

    The difference is that i++ returns the value of i before incrementing and ++i the value of i after incrementing. There is no difference if you ignore the return value, e.g. in:

    for (var i = 0; i < 10; i++) {
    
    }
    

    The habit of using ++i over i++ comes from C, where people were worried that storing the old value for i in i++ would incur a performance penalty.

提交回复
热议问题