jslint工具的一个提示是:

++和—— ++(递增)和——(递减) 众所周知,操作符会导致糟糕的代码 鼓励过度狡诈。他们 仅次于有缺陷的架构 使病毒和其他 安全威胁。这是一个加分项 选项,禁止使用这些 操作符。

我知道PHP结构像$foo[$bar++]可能很容易导致off-by-one错误,但我想不出一个更好的方法来控制循环比:

while( a < 10 ) do { /* foo */ a++; }

or

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

jslint突出显示它们是因为有一些类似的语言缺少“++”和“——”语法或处理方式不同,还是有其他避免“++”和“——”的理由,我可能忽略了?


当前回答

在我看来,“显性总是比隐性好。”因为在某些时候,你可能会对这个increments语句y+ = x++ + ++y感到困惑。一个好的程序员总是使他或她的代码更易于阅读。

其他回答

对于不熟悉自增和自减操作符的人来说,它们的“前”和“后”性质容易让人感到困惑;这是它们可能很棘手的一种方式。

我认为程序员应该精通他们所使用的语言;清楚地使用它;好好利用它。我认为他们不应该人为地削弱他们正在使用的语言。这是我的经验之谈。我曾经在一家Cobol商店的隔壁工作,他们不使用ELSE“因为它太复杂了”。荒谬还原。

As mentioned in some of the existing answers (which annoyingly I'm unable to comment on), the problem is that x++ ++x evaluate to different values (before vs after the increment), which is not obvious and can be very confusing - if that value is used. cdmckay suggests quite wisely to allow use of increment operator, but only in a way that the returned value is not used, e.g. on its own line. I would also include the standard use within a for loop (but only in the third statement, whose return value is not used). I can't think of another example. Having been "burnt" myself, I would recommend the same guideline for other languages as well.

我不同意这种过分严格是因为很多JS程序员缺乏经验的说法。这正是典型的“过于聪明”的程序员所写的东西,我敢肯定,在更传统的语言中,以及在具有此类语言背景的JS开发人员中,这种情况更为常见。

++的参数是,++不适用于会导致TypeError的字符串,这几乎总是可取的。

我的观点是在一行中单独使用++和——,如下所示:

i++;
array[i] = foo;

而不是

array[++i] = foo;

在我看来,任何超出这个范围的事情都会让一些程序员感到困惑。For循环是一个例外,因为增量操作符的使用是惯用的,因此总是明确的。