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

前端 未结 16 1236
庸人自扰
庸人自扰 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:47

    There is a history in C of doing things like:

    while (*a++ = *b++);
    

    to copy a string, perhaps this is the source of the excessive trickery he is referring to.

    And there's always the question of what

    ++i = i++;
    

    or

    i = i++ + ++i;
    

    actually do. It's defined in some languages, and in other's there's no guarantee what will happen.

    Those examples aside, I don't think there's anything more idiomatic than a for loop that uses ++ to increment. In some cases you could get away with a foreach loop, or a while loop that checked a different condtion. But contorting your code to try and avoid using incrementing is ridiculous.

提交回复
热议问题