Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

javascript - 在Javascript中声明数组时要遵循的最佳做法是什么?(What are the best practices to follow when declaring an array in Javascript?)

When I need to declare a new array I use this notation

(当我需要声明一个新数组时,我使用这种表示法)

var arr = new Array();

But when testing online, for example on jsbin , a warning signals me to "Use the array literal notation []."

(但是当在线测试时,例如在jsbin上 ,警告会向我发出“使用数组文字符号[]”的信号。)

I didn't find a reason to avoid using the constructor.

(我没有找到避免使用构造函数的理由。)

Is in some way less efficient than using [] ?

(在某种程度上比使用[]效率低吗?)

Or is it bad practice?

(还是不好的做法?)

Is there a good reason to use var arr = [];

(是否有充分的理由使用var arr = [];)

instead of var arr = new Array();

(而不是var arr = new Array();)

?

(?)

  ask by Naigel translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Mostly , people use var a = [] because Douglas Crockford says so .

(大多数情况下 ,人们使用var a = []因为Douglas Crockford这么说 。)

His reasons include the non-intuitive and inconsistent behaviour of new Array() :

(他的原因包括new Array()的非直观和不一致的行为:)

var a = new Array(5);     // an array pre-sized to 5 elements long
var b = new Array(5, 10); // an array with two elements in it

Note that there's no way with new Array() to create an array with just one pre-specified number element in it!

(请注意, new Array()没有办法创建一个只有一个预先指定的数字元素的数组!)

Using [] is actually more efficient, and safer too !

(使用[]实际上更有效, 也更安全 !)

It's possible to overwrite the Array constructor and make it do odd things, but you can't overwrite the behaviour of [] .

(可以覆盖Array构造函数并使它做奇怪的事情,但你不能覆盖[]的行为。)

Personally, I always use the [] syntax, and similarly always use {} syntax in place of new Object() .

(就个人而言,我总是使用[]语法,同样总是使用{}语法代替new Object() 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...