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开发人员中,这种情况更为常见。
在循环中,它是无害的,但在赋值语句中,它会导致意想不到的结果:
var x = 5;
var y = x++; // y is now 5 and x is 6
var z = ++x; // z is now 7 and x is 7
变量和操作符之间的空格也会导致意想不到的结果:
a = b = c = 1; a ++ ; b -- ; c; console.log('a:', a, 'b:', b, 'c:', c)
在闭包中,意外的结果也可能是一个问题:
var foobar = function(i){var count = count || i; return function(){return count++;}}
baz = foobar(1);
baz(); //1
baz(); //2
var alphabeta = function(i){var count = count || i; return function(){return ++count;}}
omega = alphabeta(1);
omega(); //2
omega(); //3
它会自动在换行后插入分号:
var foo = 1, bar = 2, baz = 3, alpha = 4, beta = 5, delta = alpha
++beta; //delta is 4, alpha is 4, beta is 6
增量前/增量后的混淆会产生差一的错误,这很难诊断。幸运的是,它们也是完全不必要的。给变量加1有更好的方法。
参考文献
JSLint帮助:增加和减少操作符