jslint工具的一个提示是:
++和——
++(递增)和——(递减)
众所周知,操作符会导致糟糕的代码
鼓励过度狡诈。他们
仅次于有缺陷的架构
使病毒和其他
安全威胁。这是一个加分项
选项,禁止使用这些
操作符。
我知道PHP结构像$foo[$bar++]可能很容易导致off-by-one错误,但我想不出一个更好的方法来控制循环比:
while( a < 10 ) do { /* foo */ a++; }
or
for (var i=0; i<10; i++) { /* foo */ }
jslint突出显示它们是因为有一些类似的语言缺少“++”和“——”语法或处理方式不同,还是有其他避免“++”和“——”的理由,我可能忽略了?
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开发人员中,这种情况更为常见。