为什么要避免 JavaScript 中的递增(“++")和递减(“--")运算符? [英] Why avoid increment ("++") and decrement ("--") operators in JavaScript?

查看:21
本文介绍了为什么要避免 JavaScript 中的递增(“++")和递减(“--")运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jslint 工具的提示之一是:

++ 和 --
++(递增)和 --(递减)众所周知,操作符会导致错误代码鼓励过度狡猾.他们仅次于有缺陷的架构在使病毒和其他安全威胁.有一个加号禁止使用这些的选项运营商.

++ and --
The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. There is a plusplus option that prohibits the use of these operators.

我知道像 $foo[$bar++] 这样的 PHP 结构很容易导致一个错误,但我想不出比 $foo[$bar++] 更好的方法来控制循环code>while( a <10 ) do {/* foo */a++;} 或 for (var i=0; i<10; i++) {/* foo */}.

I know that PHP constructs like $foo[$bar++] may easily result in off-by-one errors, but I couldn't figure out a better way to control the loop than a while( a < 10 ) do { /* foo */ a++; } or for (var i=0; i<10; i++) { /* foo */ }.

jslint 是否突出显示了它们,因为有一些类似的语言缺少++"?和--";语法或以不同方式处理它,或者是否有其他理由避免++";和--";我可能会失踪?

Is the jslint highlighting them because there are some similar languages that lack the "++" and "--" syntax or handle it differently, or are there other rationales for avoiding "++" and "--" that I might be missing?

推荐答案

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

My view is to always use ++ and -- by themselves on a single line, as in:

i++;
array[i] = foo;

代替

array[++i] = foo;

除此之外的任何事情都会让一些程序员感到困惑,而且在我看来是不值得的.For 循环是一个例外,因为增量运算符的使用是惯用的,因此总是很清楚.

Anything beyond that can be confusing to some programmers and is just not worth it in my view. For loops are an exception, as the use of the increment operator is idiomatic and thus always clear.

这篇关于为什么要避免 JavaScript 中的递增(“++")和递减(“--")运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆