Why avoid increment (“++”) and decrement (“--”) operators in JavaScript?

前端 未结 16 1010
庸人自扰
庸人自扰 2020-11-22 06:23

One of the tips for jslint tool is:

++ and --
The ++ (increment) and -- (decrement) operators have been known to contribute

16条回答
  •  醉话见心
    2020-11-22 06:49

    Consider the following code

        int a[10];
        a[0] = 0;
        a[1] = 0;
        a[2] = 0;
        a[3] = 0;
        int i = 0;
        a[i++] = i++;
        a[i++] = i++;
        a[i++] = i++;
    

    since i++ gets evaluated twice the output is (from vs2005 debugger)

        [0] 0   int
        [1] 0   int
        [2] 2   int
        [3] 0   int
        [4] 4   int
    

    Now consider the following code :

        int a[10];
        a[0] = 0;
        a[1] = 0;
        a[2] = 0;
        a[3] = 0;
        int i = 0;
        a[++i] = ++i;
        a[++i] = ++i;
        a[++i] = ++i;
    

    Notice that the output is the same. Now you might think that ++i and i++ are the same. They are not

        [0] 0   int
        [1] 0   int
        [2] 2   int
        [3] 0   int
        [4] 4   int
    

    Finally consider this code

        int a[10];
        a[0] = 0;
        a[1] = 0;
        a[2] = 0;
        a[3] = 0;
        int i = 0;
        a[++i] = i++;
        a[++i] = i++;
        a[++i] = i++;
    

    The output is now :

        [0] 0   int
        [1] 1   int
        [2] 0   int
        [3] 3   int
        [4] 0   int
        [5] 5   int
    

    So they are not the same, mixing both result in not so intuitive behavior. I think that for loops are ok with ++, but watch out when you have multiple ++ symbols on the same line or same instruction

提交回复
热议问题