开发者

Are increment/decrement operators considered bad form in Javascript? [duplicate]

开发者 https://www.devze.com 2023-04-01 13:59 出处:网络
This question already has answers here: 开发者_如何学JAVAClosed 11 years ago. Possible Duplicate:
This question already has answers here: 开发者_如何学JAVA Closed 11 years ago.

Possible Duplicate:

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

I've recently been running all my javascript through JSLint and it always gives me Unexpected '++' on my increment operators. I've also noticed there is a JSLint option to tolerate ++/--.

Is it considered bad form to use i++/i--?


If I understand correctly, the reason it's in JSLint is because there's a significant difference between ++i and i++, and many developers don't necessarily appreciate the implications of being specific about when the addition is done, in relation to other operations around it.

for example:

var i = 0;
if(i++) {
    //does this get run or not?
}
if(--i) {
    //and what about this one?
}

This is why Crockford considers it bad practice, and prefers the more explicit +=1.

However, in general, I don't have this kind of issue with ++; I'm perfectly happy to use it, and I would ignore JSLint telling me not to (most of the time!).

This is the important thing about JSLint -- it doesn't tell you about actual errors; everything it tells you is a suggestion. Some of them are excellent suggestions (eg you should never ever use with); some are good suggestions that indicate poor code; and some of them are only a problem some of the time and should be considered individually. As a developer it is more important that you need to know why it's making its suggesting than it is to actually fix them. Once you understand the reasons for them being pointed out, you are in a position to decide for yourself whether a given instance of it in your code is a problem or not and how to fix it.

Hope that helps.


No, I suppose this could get argumentative, but seriously everything learns about this operator very soon in their educations or books or whatever. This suggestion annoys me.


I don't think it's specifically considered bad form in Javascript, it's just hard for most programmers to use these operators correctly in general.


Instead of using ++/-- it's considered a better practice to use +=/-=.

x += 1; instead of x++;.

This is supposed to increase readability and avoid typing mistakes due to excessive use of "code tricks".

Personally I find more useful to use this method instead of the default ++/-- operators, as the number will be colored by the IDE and it's easier to spot.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号