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
181 views
in Technique[技术] by (71.8m points)

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 []."

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 = []; instead of var arr = new Array();?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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.

His reasons include the non-intuitive and inconsistent behaviour of 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!

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 [].

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


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

...