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

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

问题描述

jslint工具提示之一是:


++和 -

++(增量)和 - (减量)
运算符众所周知,通过
鼓励过多的诡计会导致糟糕的代码。他们
仅次于故障架构
,可以实现病毒和其他
安全威胁。有一个plusplus
选项禁止使用这些
运算符。

++ 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.

我知道PHP构造类似 $ foo [$ bar ++] 可能很容易导致一个一个错误,但我无法找到一个比<$ c更好的方法来控制循环$ c> while(a< 10)do {/ * foo * / a ++; } 或 for(var i = 0; i< 10; i ++){/ * foo * /}

I know that PHP constructs like $foo[$bar++] has may easily result with 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循环是一个例外,因为使用increment运算符是惯用的,因此总是清晰的。

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天全站免登陆