Avoid creating a new object by using
new Object()
. Use the object literal syntax{}
instead.避免通过使用
new Object()
创建新对象。 请改用对象文字语法{}
。Same thing for arrays, favor
[]
overnew Array()
.数组也一样,相对于
new Array()
更喜欢[]
。Avoid blocks except where statements require them (
if
,switch
, loops,try
).避免使用块,除非语句需要它们(
if
,switch
,循环,try
)。Never assign inside an
if
ofwhile
statements condition part切勿在
if
ofwhile
语句条件部分内分配Never use
==
and!=
. Use===
and!==
instead.切勿使用
==
和!=
。 使用===
和!==
代替。Never use
eval
. Why? It has performance issues (it runs the interpreter/compiler), it has security issues (code injection if used with user input), difficulties in debugging.永远不要使用
eval
。 为什么? 它存在性能问题(运行解释器/编译器),存在安全性问题(如果与用户输入一起使用则注入代码),调试困难。Never use
with
, as it modifies the scope chain and can be a source of confusion.切勿
with
使用,因为它会修改范围链,并可能引起混乱。Always pass functions to
setTimeout
andsetInterval
始终将函数传递给
setTimeout
和setInterval
Never use
Array
as an associative arrays, useObject
instead. The part of theArray
object that provides that functionality is in fact provided by theObject
prototype, so you could really have used aDate
object for that same thing.切勿将
Array
用作关联数组,而应使用Object
。 实际上,提供对象功能的Array
对象部分是由Object
原型提供的,因此您实际上可以将Date
对象用于同一件事。Don’t use
\
at the end of a string to create a multiline string, it’s not part of ECMAScript. Use string concatenation' string1 ' + ' string2 '
instead不要在字符串的末尾使用
\
来创建多行字符串,因为它不是ECMAScript的一部分。 使用字符串串联' string1 ' + ' string2 '
Never modify the prototypes of the built-in objects
Object
andArray
. Modify other prototypes of other objects such asFunction
with caution as it could lead to bugs hard to debug.切勿修改内置对象
Object
和Array
的原型。 请谨慎修改其他对象(例如Function
其他原型,因为这可能会导致难以调试的错误。
翻译自: https://flaviocopes.com/things-to-avoid-in-javascript-bad-parts/