++someVariable vs. someVariable++ in JavaScript

后端 未结 6 2001
长发绾君心
长发绾君心 2020-11-22 02:02

In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences b

6条回答
  •  野性不改
    2020-11-22 03:01

    • ++x increments the value, then evaluates and stores it.
    • x++ evaluates the value, then increments and stores it.
    var n = 0, m = 0;
    
    alert(n++); /* Shows 0, then stores n = 1 */
    alert(++m); /* Shows 1, then stores m = 1 */
    

    Note that there are slight performance benefits to using ++x where possible, because you read the variable, modify it, then evaluate and store it. Versus the x++ operator where you read the value, evaluate it, modify it, then store it.

提交回复
热议问题